2017-06-16 113 views
0

我有一個需要基本身份驗證的Web服務。我用一個小型的java程序測試它。使用C進行Web服務的基本身份驗證#

顯着:

... 
String authorization = s + ':' + (s1 != null ? s1 : ""); 
authorization = Base64.getEncoder().encodeToString(authorization2.getBytes()); 
httpurlconnection.setRequestProperty("Authorization", "Basic " + authorization); 
.... 

這工作得很好。但是我必須用C#程序來處理這個問題。我通過導入wsdl文件在我的項目中添加「Service Reference」。 很多搜​​索之後,我認爲這將是這筆交易:

WSHttpBinding binding = new WSHttpBinding(); 
binding.Name = "pisconfigwebserviceSOAP"; 
EndpointAddress epAdd = new EndpointAddress(remoteAddress); 
myWebserviceClient client = new myWebserviceClient(binding, epAdd); 

ContractDescription cd = ContractDescription.GetContract(typeof(myWebservice), typeof(myWebserviceClient)); 
    client.Endpoint.Contract = cd; 

// this part should add the Basic Authentication to the header. Or not? 
using (OperationContextScope scope = new OperationContextScope(client.InnerChannel)) { 
    var httpRequestProperty = new HttpRequestMessageProperty(); 
    httpRequestProperty.Headers.Add(HttpRequestHeader.Authorization, "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(mUserName + ":" + mPassword))); 
    OperationContext.Current.OutgoingMessageProperties.Add(HttpRequestMessageProperty.Name, httpRequestProperty); 

    int result = client.AddOrUpdate(obj); 
} 

我不知道我做錯了,嘗試了很多很多不同的東西,我堅持在這裏。 我將不勝感激任何幫助。謝謝

回答

0

試試看你的代碼的最後一節。當我測試這個,我可以看到「授權」標題被填充。

using (var scope = new OperationContextScope(client.InnerChannel)) 
{ 
    var hrmp = new HttpRequestMessageProperty(); 
    hrmp.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(mUserName + ":" + mPassword)); 

    OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = hrmp; 

    int result = client.AddOrUpdate(obj); 
} 
相關問題