使用C#对Web服务进行基本身份验证

时间:2017-06-16 11:12:14

标签: c# web-services basic-authentication service-reference

我有一个需要基本身份验证的Web服务。我用一个小的java程序测试它。

基本上:

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

这很好用。但我必须用C#程序处理这个问题。我通过导入wsdl文件在我的项目中添加了“服务引用”。 经过大量的搜索,我认为这将是一笔交易:

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

我不知道我做错了什么,尝试了许多不同的事情,我坚持到这里。 我将不胜感激任何帮助。感谢

1 个答案:

答案 0 :(得分: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);
}