2010-05-04 58 views
0

我試圖在C#中使用下面的代碼以編程方式創建REST客戶端代理,但我不斷收到CommunicationException錯誤。我錯過了什麼嗎?以編程方式創建WCF REST客戶端代理(在C#中)

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

我不還不明白爲什麼,但在另一個問題中,問題是將webhttpbinding添加到工廠端點行爲:factory.Endpoint.Behaviors.Add(new WebHttpBehavior()); – 2010-07-04 15:50:41

+0

也沒有工作。還有其他建議嗎? – Tawani 2010-07-07 20:17:59

回答

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