5

我从 WSDL 生成了一个服务引用。我已经成功地针对服务参考对客户端进行了编码。我一直在使用 serviceRef.serviceMethod(params...) 模式来调用基于服务的方法。现在我需要将 http 标头添加到我发送的消息中。我找不到在哪里将它们设置为服务的所有消息的默认值,也找不到在调用某些方法时可以在哪里设置它们。有些文章建议我可以使用 IClientMessageInspector,但实现似乎很复杂。有什么建议么?

4

1 回答 1

4

从很多地方借来的,但主要是:

http://msmvps.com/blogs/paulomorgado/archive/2007/04/27/wcf-building-an-http-user-agent-message-inspector.aspx

我简化了,但我认为我有一个可以添加自定义 httpheaders 的实现。

    public class HttpHeaderMessageInspector : IClientMessageInspector
    {
        private readonly Dictionary<string, string> _httpHeaders;

        public HttpHeaderMessageInspector(Dictionary<string, string> httpHeaders)
        {
            this._httpHeaders = httpHeaders;
        }

        public void AfterReceiveReply(ref Message reply, object correlationState) { }

        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            HttpRequestMessageProperty httpRequestMessage;
            object httpRequestMessageObject;

            if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out httpRequestMessageObject))
            {
                httpRequestMessage = httpRequestMessageObject as HttpRequestMessageProperty;

                foreach (var httpHeader in _httpHeaders)
                {
                    httpRequestMessage.Headers[httpHeader.Key] = httpHeader.Value;
                }
            }
            else
            {
                httpRequestMessage = new HttpRequestMessageProperty();

                foreach (var httpHeader in _httpHeaders)
                {
                    httpRequestMessage.Headers.Add(httpHeader.Key, httpHeader.Value);
                }
                request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage);
            }
            return null;
        }
    }

internal class HttpHeadersEndpointBehavior : IEndpointBehavior
    {
        private readonly Dictionary<string,string> _httpHeaders;

        public HttpHeadersEndpointBehavior(Dictionary<string, string> httpHeaders)
        {
            this._httpHeaders = httpHeaders;
        }
        public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) { }

        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
            var inspector = new HttpHeaderMessageInspector(this._httpHeaders);

            clientRuntime.MessageInspectors.Add(inspector);
        }

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

然后在更新我的服务参考后:

    var httpHeaders = new Dictionary<string, string>();
    httpHeaders.Add("header1", "value1");
    httpHeaders.Add("header2", "value2");

    _serviceRef.Endpoint.Behaviors.Add(new HttpHeadersEndpointBehavior(httpHeaders));

没有其他东西需要改变。如果您想到更简单的方法,请告诉我。

于 2012-07-18T14:25:59.130 回答