Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add the ability to replace or customize the HttpMessageHandler #2534

Merged
merged 1 commit into from
Feb 22, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ internal class HttpChannelFactory<TChannel>
private SecurityTokenManager _securityTokenManager;
private TransferMode _transferMode;
private ISecurityCapabilities _securityCapabilities;
private Func<HttpClientHandler, HttpMessageHandler> _httpMessageHandlerFactory;
private WebSocketTransportSettings _webSocketSettings;
private Lazy<string> _webSocketSoapContentType;
private SHA512 _hashAlgorithm;
Expand Down Expand Up @@ -130,6 +131,7 @@ internal HttpChannelFactory(HttpTransportBindingElement bindingElement, BindingC

_channelCredentials = context.BindingParameters.Find<SecurityCredentialsManager>();
_securityCapabilities = bindingElement.GetProperty<ISecurityCapabilities>(context);
_httpMessageHandlerFactory = context.BindingParameters.Find<Func<HttpClientHandler, HttpMessageHandler>>();

_webSocketSettings = WebSocketHelper.GetRuntimeWebSocketSettings(bindingElement.WebSocketSettings);
_clientWebSocketFactory = ClientWebSocketFactory.GetFactory();
Expand Down Expand Up @@ -331,7 +333,13 @@ internal async Task<HttpClient> GetHttpClientAsync(EndpointAddress to,
clientHandler.Credentials = credential;
}

httpClient = new HttpClient(clientHandler);
HttpMessageHandler handler = clientHandler;
if(_httpMessageHandlerFactory!= null)
{
handler = _httpMessageHandlerFactory(clientHandler);
}

httpClient = new HttpClient(handler);

if(!_keepAliveEnabled)
httpClient.DefaultRequestHeaders.ConnectionClose = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// See the LICENSE file in the project root for more information.

using System;
using System.Net.Http;
using System.ServiceModel;
using System.ServiceModel.Channels;
using Infrastructure.Common;
Expand Down Expand Up @@ -79,4 +80,100 @@ public static void HttpKeepAliveDisabled_Echo_RoundTrips_True()
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}

[WcfFact]
[OuterLoop]
public static void HttpMessageHandlerFactory_Success()
{
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
string testString = "Hello";
Binding binding = null;

try
{
// *** SETUP *** \\
binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic));
var handlerFactoryBehavior = new HttpMessageHandlerBehavior();
bool handlerCalled = false;
handlerFactoryBehavior.OnSending = (message, token) =>
{
handlerCalled = true;
return null;
};
factory.Endpoint.Behaviors.Add(handlerFactoryBehavior);
serviceProxy = factory.CreateChannel();

// *** EXECUTE *** \\
string result = serviceProxy.Echo("Hello");

// *** VALIDATE *** \\
Assert.True(handlerCalled, "Error: expected client to call intercepting handler");
Assert.True(result == testString, String.Format("Error: expected response from service: '{0}' Actual was: '{1}'", testString, result));

// *** CLEANUP *** \\
factory.Close();
((ICommunicationObject)serviceProxy).Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}

[WcfFact]
[OuterLoop]
public static void HttpMessageHandlerFactory_ModifyContent_Success()
{
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
string testString = "Hello";
string substituteString = "World";
Binding binding = null;

try
{
// *** SETUP *** \\
binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic));
var handlerFactoryBehavior = new HttpMessageHandlerBehavior();
handlerFactoryBehavior.OnSending = (message, token) =>
{
var oldContent = message.Content;
string requestMessageBody = oldContent.ReadAsStringAsync().Result;
requestMessageBody = requestMessageBody.Replace(testString, substituteString);
message.Content = new StringContent(requestMessageBody);
foreach (var header in oldContent.Headers)
{
if (!header.Key.Equals("Content-Length") && message.Content.Headers.Contains(header.Key))
{
message.Content.Headers.Remove(header.Key);
}

message.Content.Headers.Add(header.Key, header.Value);
}

return null;
};
factory.Endpoint.Behaviors.Add(handlerFactoryBehavior);
serviceProxy = factory.CreateChannel();

// *** EXECUTE *** \\
string result = serviceProxy.Echo("Hello");

// *** VALIDATE *** \\
Assert.True(result == substituteString, String.Format("Error: expected response from service: '{0}' Actual was: '{1}'", testString, result));

// *** CLEANUP *** \\
factory.Close();
((ICommunicationObject)serviceProxy).Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

public class HttpMessageHandlerBehavior : IEndpointBehavior
{
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
bindingParameters.Add(new Func<HttpClientHandler, HttpMessageHandler>(GetHttpMessageHandler));
}

public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime) { }

public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) { }

public void Validate(ServiceEndpoint endpoint) { }

public HttpMessageHandler GetHttpMessageHandler(HttpClientHandler httpClientHandler)
{
return new InterceptingHttpMessageHandler(httpClientHandler, this);
}

public Func<HttpRequestMessage, CancellationToken, HttpResponseMessage> OnSending { get; set; }
public Func<HttpResponseMessage, CancellationToken, HttpResponseMessage> OnSent { get; set; }

}

public class InterceptingHttpMessageHandler : DelegatingHandler
{
private readonly HttpMessageHandlerBehavior _parent;

public InterceptingHttpMessageHandler(HttpMessageHandler innerHandler, HttpMessageHandlerBehavior parent)
{
InnerHandler = innerHandler;
_parent = parent;
}

protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
HttpResponseMessage response;
if (_parent.OnSending != null)
{
response = _parent.OnSending(request, cancellationToken);
if (response != null)
return response;
}

response = await base.SendAsync(request, cancellationToken);

if (_parent.OnSent != null)
{
return _parent.OnSent(response, cancellationToken);
}

return response;
}
}