2014-07-02 131 views
0

您好,我在服务器上有一个Web服务。我使用基于BasicHttpBinding的客户端连接到此Web服务。我们添加到此服务基于cookie的身份验证,现在我想添加对我的客户的cookie的支持。将Cookie添加到BasicHttpBinding

所以这是我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; 
} 

我知道价值所以可以说: string cookiecontent =“blabla”;

现在我需要将这个cookie添加到我的客户端,每当我调用CheckAuthorization时,cookie都会通过。任何想法如何做到这一点?我以异常结束“HTTP请求被客户端身份验证方案'Basic'禁止。”

+0

我有人打像我这样的问题,有一个在HTTP上的主题一个很好的博文:/ /megakemp.com/2009/02/06/managing-shared-cookies-in-wcf/ –

回答

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; 
相关问题