C# 向BasicHttpBinding添加cookie
您好,我在服务器上有一个web服务。我正在使用基于BasicHttpBinding的客户端连接此web服务。我们向该服务添加了基于cookie的身份验证,现在我想向我的客户端添加对cookie的支持 这是我的MyServiceClient类:C# 向BasicHttpBinding添加cookie,c#,.net,wcf,cookies,basichttpbinding,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.
[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);
}
... ...
}
这是我的CheckAuthorization实现:
public bool CheckAuthorization()
{
CheckAuthorizationRequest inValue = new CheckAuthorizationRequest();
CheckAuthorizationResponse retVal = ((IMyServiceClient)(this)).CheckAuthorization(inValue);
return retVal.checkAuthorizationResult;
}
我知道饼干的价值,所以让我们说:
字符串cookiecontent=blabla
现在我需要将这个cookie添加到我的客户端,每当我调用CheckAuthorization时,cookie就会通过。有什么办法吗?我将以例外结束HTTP请求,客户端身份验证方案“Basic”禁止HTTP请求。因此我通过添加以下内容解决了此问题:
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;
我和任何一个像我一样提出这个问题的人,都有一篇关于这个问题的好博客
var binding = new BasicHttpBinding("MyServiceSoapBinding");
binding.AllowCookies = false;