How to add a custom HTTP header to every WCF call?

后端 未结 13 2298
不知归路
不知归路 2020-11-22 05:33

I have a WCF service that is hosted in a Windows Service. Clients that using this service must pass an identifier every time they\'re calling service methods (because that i

13条回答
  •  长情又很酷
    2020-11-22 06:17

    This is what worked for me, adapted from Adding HTTP Headers to WCF Calls

    // Message inspector used to add the User-Agent HTTP Header to the WCF calls for Server
    public class AddUserAgentClientMessageInspector : IClientMessageInspector
    {
        public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, IClientChannel channel)
        {
            HttpRequestMessageProperty property = new HttpRequestMessageProperty();
    
            var userAgent = "MyUserAgent/1.0.0.0";
    
            if (request.Properties.Count == 0 || request.Properties[HttpRequestMessageProperty.Name] == null)
            {
                var property = new HttpRequestMessageProperty();
                property.Headers["User-Agent"] = userAgent;
                request.Properties.Add(HttpRequestMessageProperty.Name, property);
            }
            else
            {
                ((HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name]).Headers["User-Agent"] = userAgent;
            }
            return null;
        }
    
        public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
        }
    }
    
    // Endpoint behavior used to add the User-Agent HTTP Header to WCF calls for Server
    public class AddUserAgentEndpointBehavior : IEndpointBehavior
    {
        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
            clientRuntime.MessageInspectors.Add(new AddUserAgentClientMessageInspector());
        }
    
        public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
        {
        }
    
        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        {
        }
    
        public void Validate(ServiceEndpoint endpoint)
        {
        }
    }
    

    After declaring these classes you can add the new behavior to your WCF client like this:

    client.Endpoint.Behaviors.Add(new AddUserAgentEndpointBehavior());
    

提交回复
热议问题