代码之家  ›  专栏  ›  技术社区  ›  Tawani

通过编程(在C中)创建一个WCF REST客户端代理

  •  0
  • Tawani  · 技术社区  · 15 年前

    我正尝试使用下面的代码在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
    
    1 回复  |  直到 15 年前
        1
  •  0
  •   Tawani    13 年前

    为了使用表单身份验证,我必须物理地重写身份验证头,如下所示:

    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());
    }
    
    推荐文章