【问题标题】:Basic Authentication to web service with C#使用 C# 对 Web 服务进行基本身份验证
【发布时间】:2023-04-04 09:28:02
【问题描述】:

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

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

【问题讨论】:

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


    【解决方案1】:

    在代码的最后一部分试试这个。当我对此进行测试时,我可以看到“授权”标题已填充。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-28
      • 1970-01-01
      • 2014-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多