Adding cookie to BasicHttpBinding

本文关键字:BasicHttpBinding to cookie Adding | 更新日期: 2023-09-27 18:11:03

你好,我在服务器上有一个web服务。我正在连接到这个web服务与客户端基于BasicHttpBinding。我们为这个服务添加了基于cookie的身份验证,现在我想在我的客户端添加对cookie的支持。

这是MyServiceClient类:

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public partial class MyServiceClient: System.ServiceModel.ClientBase<IMyServiceClient>, IMyServiceClient
{
    ... ctors ....
   [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
    CheckAuthorizationResponse IMyServiceClient.CheckAuthorization(CheckAuthorizationRequest request)
    {
        return base.Channel.CheckAuthorization(request);
    }
    ... ...
}

创建客户端:

var binding = new BasicHttpBinding("MyServiceSoapBinding");
binding.AllowCookies = true;       // trying to experiment with this
var client = new MyServiceClient(binding, new EndpointAddress(endpointAddr),installation.CertThumbprint);
return client;

这是我的CheckAuthorization实现:

public bool CheckAuthorization()
{
    CheckAuthorizationRequest inValue = new CheckAuthorizationRequest();
    CheckAuthorizationResponse retVal = ((IMyServiceClient)(this)).CheckAuthorization(inValue);
    return retVal.checkAuthorizationResult;
}

和我知道cookie的值,所以我们说:String cookicontent = "blabla";

,现在我需要添加这个cookie到我的客户端,每当我调用CheckAuthorization cookie将通过。有什么办法吗?我以例外结束"HTTP请求被禁止与客户端身份验证方案'基本'。"

Adding cookie to BasicHttpBinding

所以我通过添加:

来解决这个问题
using (new OperationContextScope(client.InnerChannel))
{
    var endPoint = new EndpointAddress(url);
    var authCookie = new System.Net.Cookie("Auth", cookie);
    var cookies = new CookieContainer();
    cookies.Add(new Uri(url), authCookie);
    var httpRequest = new System.ServiceModel.Channels.HttpRequestMessageProperty();
    OperationContext.Current.OutgoingMessageProperties.Add(System.ServiceModel.Channels.HttpRequestMessageProperty.Name, httpRequest);
    httpRequest.Headers.Add(HttpRequestHeader.Cookie, cookies.GetCookieHeader(endPoint.Uri));
    var authChecked = client.CheckAuthorization(request);
}

我还必须加上:

var binding = new BasicHttpBinding("MyServiceSoapBinding");
binding.AllowCookies = false;