How to add custom Http Header for C# Web Service Client consuming Axis 1.4 Web service

前端 未结 7 1762
离开以前
离开以前 2020-11-29 20:33

I\'m trying to write a web service client in c# which the webservice is Java Axis 1.4. Axis service requires the Authorization: Basic Base64EncodedToken hea

7条回答
  •  误落风尘
    2020-11-29 20:46

    Instead of modding the auto-generated code or wrapping every call in duplicate code, you can inject your custom HTTP headers by adding a custom message inspector, it's easier than it sounds:

    public class CustomMessageInspector : IClientMessageInspector
    {
        readonly string _authToken;
    
        public CustomMessageInspector(string authToken)
        {
            _authToken = authToken;
        }
    
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            var reqMsgProperty = new HttpRequestMessageProperty();
            reqMsgProperty.Headers.Add("Auth-Token", _authToken);
            request.Properties[HttpRequestMessageProperty.Name] = reqMsgProperty;
            return null;
        }
    
        public void AfterReceiveReply(ref Message reply, object correlationState)
        { }
    }
    
    
    public class CustomAuthenticationBehaviour : IEndpointBehavior
    {
        readonly string _authToken;
    
        public CustomAuthenticationBehaviour (string authToken)
        {
            _authToken = authToken;
        }
        public void Validate(ServiceEndpoint endpoint)
        { }
    
        public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
        { }
    
        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        { }
    
        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
            clientRuntime.ClientMessageInspectors.Add(new CustomMessageInspector(_authToken));
        }
    }
    

    And when instantiating your client class you can simply add it as a behavior:

    this.Endpoint.EndpointBehaviors.Add(new CustomAuthenticationBehaviour("Auth Token"));
    

    This will make every outgoing service call to have your custom HTTP header.

提交回复
热议问题