将Cookie添加到BasicHttpBinding

时间:2014-07-02 11:39:06

标签: c# .net wcf cookies basichttpbinding

您好我在服务器上有一个Web服务。我正在使用基于BasicHttpBinding的客户端连接到此Web服务。我们在此服务中添加了基于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 cookiecontent =&#34; blabla&#34 ;;

现在我需要将此cookie添加到我的客户端,每当我调用CheckAuthorization时,cookie都会通过。有什么想法怎么做?我以异常&#34结束; HTTP请求被禁止使用客户端身份验证方案&#39; Basic&#39;。&#34;

1 个答案:

答案 0 :(得分:0)

所以我通过添加:

来解决这个问题
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;