首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >以编程方式创建WCF REST客户端代理(在C#中)

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

Stack Overflow用户
提问于 2010-05-04 22:25:17
回答 1查看 3.2K关注 0票数 0

我试图使用下面的代码在C#中以编程方式创建一个REST客户端代理,但我一直收到一个CommunicationException错误。我是不是遗漏了什么?

代码语言:javascript
复制
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;
    }
}

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

代码语言:javascript
复制
IMyRestService proxy = WebProxyFactory.Create<IMyRestService>(url, usr, pwd);
var result = proxy.GetSomthing(); // Fails right here
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-01-13 23:05:24

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

代码语言:javascript
复制
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());
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2766128

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档