2017-06-16 115 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); 
} 
相关问题