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



我有一个需要基本身份验证的 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);
}

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

在代码的最后一部分尝试此操作。当我对此进行测试时,我可以看到填充了"授权"标头。

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

相关内容

  • 没有找到相关文章

最新更新