Created
August 8, 2011 23:22
-
-
Save pmhsfelix/1133027 to your computer and use it in GitHub Desktop.
HTTP intermediary using WCF Web API message handlers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace WcfWebApi.Preview4.Explorations.MessageHandlers | |
{ | |
class ProxyMessageHandler : DelegatingChannel | |
{ | |
private readonly HttpClient _client = new HttpClient(); | |
public ProxyMessageHandler(HttpMessageChannel innerChannel) | |
: base(innerChannel) | |
{ | |
} | |
protected override Task<HttpResponseMessage> SendAsync( | |
HttpRequestMessage request, CancellationToken cancellationToken) | |
{ | |
try | |
{ | |
var req = new HttpRequestMessage | |
{ | |
RequestUri = | |
new Uri("http://" + request.Headers.Host + request.RequestUri.PathAndQuery), | |
Method = request.Method | |
}; | |
if (req.Method == HttpMethod.Post || req.Method == HttpMethod.Put) | |
{ | |
req.Content = request.Content; | |
} | |
foreach (var h in request.Headers.Where(h => !h.Key.StartsWith("Proxy-"))) | |
{ | |
req.Headers.Add(h.Key, h.Value); | |
} | |
var resp = _client.SendAsync(req,HttpCompletionOption.ResponseHeadersRead); | |
resp.ContinueWith(t => TraceResponse(req,t)); | |
return resp.ContinueWith(t => | |
{ | |
//t.Result.Headers.TransferEncodingChunked = false; | |
t.Result.Headers.Remove("Transfer-Encoding"); | |
return t.Result; | |
}); | |
} | |
catch (Exception e) | |
{ | |
Console.WriteLine(e); | |
throw; | |
} | |
} | |
private readonly object _traceLock = new object(); | |
private void TraceResponse(HttpRequestMessage req, Task<HttpResponseMessage> resp) | |
{ | |
lock (_traceLock) | |
{ | |
try | |
{ | |
Console.WriteLine("++++++++++++++++++++++++++++++"); | |
Console.WriteLine(req); | |
Console.WriteLine(resp.Result); | |
Console.WriteLine("------------------------------"); | |
} | |
catch (Exception e) | |
{ | |
Console.WriteLine(e); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment