以编程方式创建 WCF REST 客户端代理(在 C# 中)

Posted

技术标签:

【中文标题】以编程方式创建 WCF REST 客户端代理(在 C# 中)【英文标题】:Create a WCF REST Client Proxy Programatically (in C#) 【发布时间】:2011-02-15 12:07:41 【问题描述】:

我正在尝试使用以下代码在 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

【问题讨论】:

我还不明白为什么,但在另一个问题中,问题是将 webhttpbinding 添加到工厂端点行为: factory.Endpoint.Behaviors.Add(new WebHttpBehavior()); 那也没用。还有其他建议吗? 【参考方案1】:

为了让它与表单身份验证一起使用,我必须按如下方式物理覆盖身份验证标头:

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());

【讨论】:

以上是关于以编程方式创建 WCF REST 客户端代理(在 C# 中)的主要内容,如果未能解决你的问题,请参考以下文章

在 C# 中以编程方式创建 WCF 客户端的标头(wsse)部分

为 Rest Web 服务创建 WCF 代理

为整个应用程序保留一个 wcf 客户端代理

WCF REST (WebHttpBinding) 可以遵守 PROGRAMMATIC 输出缓存策略吗?

以编程方式使用证书身份验证配置 WCF 服务客户端

如何以编程方式为 WCF 服务创建自签名证书?