Silverlight不支持HttpWebRequest上的标头

时间:2016-02-24 16:27:34

标签: c# wcf silverlight proxy

我正在处理一项要求,我必须在Silverlight应用程序中向IIS中运行的WCF服务中的所有HTTP发布请求添加自定义标头。

我实现了IClientMessageInspector和IEndpointBehavior,并以编程方式将行为添加到客户端代理。我按照这里发布的说明操作: http://blogs.msmvps.com/paulomorgado/2007/04/26/wcf-building-an-http-user-agent-message-inspector/ http://adilmughal.com/blog/2011/10/wcf-custom-header-with-silverlight/

IClientMessageInspector:

public class HttpUserAgentMessageInspector : IClientMessageInspector
{
    private const string UserAgentHttpHeader = "user-agent";

    private readonly string _userAgent;

    public HttpUserAgentMessageInspector(string userAgent)
    {
        _userAgent = userAgent;
    }

    #region IClientMessageInspector Members

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

    public object BeforeSendRequest(ref Message request, System.ServiceModel.IClientChannel channel)
    {
        HttpRequestMessageProperty httpRequestMessage;
        object httpRequestMessageObject;
        if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out httpRequestMessageObject))
        {
            httpRequestMessage = (HttpRequestMessageProperty)httpRequestMessageObject;
            if (string.IsNullOrEmpty(httpRequestMessage.Headers[UserAgentHttpHeader]))
            {
                httpRequestMessage.Headers[UserAgentHttpHeader] = _userAgent;
            }
        }
        else
        {
            httpRequestMessage = new HttpRequestMessageProperty();
            httpRequestMessage.Headers[UserAgentHttpHeader] = _userAgent;
            request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage);
        }
        return null;
    }

    #endregion
}

IEndpointBehavior:

public class HttpUserAgentEndpointBehavior : IEndpointBehavior
{
    private readonly string _mUserAgent;

    public HttpUserAgentEndpointBehavior(string userAgent)
    {
        _mUserAgent = userAgent;
    }

    #region IEndpointBehavior Members

    public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
    {
    }

    public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
    {
        var inspector = new HttpUserAgentMessageInspector(_mUserAgent);
        clientRuntime.MessageInspectors.Add(inspector);
    }

    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
    {
    }

    public void Validate(ServiceEndpoint endpoint)
    {
    }

    #endregion
}

向代理添加行为。请注意,我已将客户端代理的实例化抽象到此ClientManager类中。我的Silverlight应用程序具有多个服务,这些服务都需要相同的自定义配置,该配置通过此管理器应用。为简洁起见,我删除了不相关的代码。

public class ClientManager<TClient, TService> : NotificationObject, IClientManager<TClient, TService>
    where TClient : ClientBase<TService>, ICommunicationObject
    where TService : class
{
    private static IClientFactory _factory = new ClientFactory();
    private TClient _client;

    /// <summary>
    /// Instantiates the manager and the client.
    /// </summary>
    /// <param name="args">The arguments used to construct the client.</param>
    public ClientManager(params object[] args)
    {
        try
        {
            _client = _factory.Create<TClient, TService>(args);

            // Add custom behavior to support custom HTTP headers
            _client.Endpoint.Behaviors.Add(new HttpUserAgentEndpointBehavior("this is a test"));
        }
        catch (Exception exc)
        {
            // The factory may throw an exception when it cannot instantiate the client.
            FaultException = exc;
            throw;
        }

        Client.Faulted += Client_Faulted;
    }
}

现在,当我运行应用程序时,我在服务对WCF服务的第一次调用中得到以下异常

  

NotSupportedException异常。 &#39;用户代理&#39; HttpWebRequest上的标题不是   Silverlight支持。

在客户端代理自动生成的代码中:

        public System.IAsyncResult BeginAutoLoginUser(System.AsyncCallback callback, object asyncState) {
            object[] _args = new object[0];
            System.IAsyncResult _result = base.BeginInvoke("AutoLoginUser", _args, callback, asyncState);
            return _result;
        }

为什么这不起作用?

0 个答案:

没有答案