0

我正在尝试使用以下代码在 C# 中以编程方式创建 REST 客户端代理,但我不断收到 CommunicationException 错误。我错过了什么吗?

public static class WebProxyFactory
{
    public static T Create<T>(string url) where T : class
    {
        ServicePointManager.Expect100Continue = false;
        WebHttpBinding binding = new WebHttpBinding();

        binding.MaxReceivedMessageSize = 1000000;

        WebChannelFactory<T> factory =
          new WebChannelFactory<T>(binding, new Uri(url));

        T proxy = factory.CreateChannel();

        return proxy;
    }

    public static T Create<T>(string url, string userName, string password)
      where T : class
    {
        ServicePointManager.Expect100Continue = false;
        WebHttpBinding binding = new WebHttpBinding();

        binding.Security.Mode =
          WebHttpSecurityMode.TransportCredentialOnly;
        binding.Security.Transport.ClientCredentialType =
          HttpClientCredentialType.Basic;
        binding.UseDefaultWebProxy = false;

        binding.MaxReceivedMessageSize = 1000000;

        WebChannelFactory<T> factory =
          new WebChannelFactory<T>(binding, new Uri(url));

        ClientCredentials credentials = factory.Credentials;
        credentials.UserName.UserName = userName;
        credentials.UserName.Password = password;

        T proxy = factory.CreateChannel();

        return proxy;
    }
}

这样我就可以按如下方式使用它:

IMyRestService proxy = WebProxyFactory.Create<IMyRestService>(url, usr, pwd);
var result = proxy.GetSomthing(); // Fails right here
4

1 回答 1

0

为此,要使用表单身份验证,我必须物理覆盖身份验证标头,如下所示:

var proxy = WebProxyFactory.Create<ITitleWorldService>(url, userName, password);

using (new OperationContextScope((IContextChannel)proxy))
{
    var authorizationToken = GetBasicAuthorizationToken(userName, password);
    var httpRequestProperty = new HttpRequestMessageProperty();
    httpRequestProperty.Headers[System.Net.HttpRequestHeader.Authorization] = authorizationToken;
    OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;

    //var response = proxy.DoWork();    
    Console.WriteLine(proxy.SayHello());
}
于 2012-01-13T15:05:23.800 回答