forked from aspnet/AspNetWebStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConvertToStreamMessageHandler.cs
More file actions
48 lines (43 loc) · 1.7 KB
/
Copy pathConvertToStreamMessageHandler.cs
File metadata and controls
48 lines (43 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace System.Web.Http.Util
{
internal class ConvertToStreamMessageHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
HttpContent requestContent = await ToStreamContent(request.Content);
request.Content = requestContent;
HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
HttpContent responseContent = await ToStreamContent(response.Content);
response.Content = responseContent;
return response;
}
private static Task<HttpContent> ToStreamContent(HttpContent content)
{
ObjectContent objectContent = content as ObjectContent;
if (objectContent != null)
{
return ToStreamContent(objectContent);
}
else
{
return Task.FromResult(content);
}
}
private static async Task<HttpContent> ToStreamContent(ObjectContent content)
{
Stream stream = await content.ReadAsStreamAsync();
StreamContent streamContent = new StreamContent(stream);
foreach (var header in content.Headers)
{
streamContent.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
return streamContent;
}
}
}