如何在 WPF 应用程序中 SOAP 客户端的“Set-Cookie”标头响应的新请求中设置“Cookie”标头
Posted
技术标签:
【中文标题】如何在 WPF 应用程序中 SOAP 客户端的“Set-Cookie”标头响应的新请求中设置“Cookie”标头【英文标题】:How do I set "Cookie" header in a new request from "Set-Cookie" header response for a SOAP client in a WPF application 【发布时间】:2019-06-12 04:24:14 【问题描述】:我正在将我的 WPF 应用程序与 2 个 WCF 应用程序集成(一个是“身份验证应用程序”,另一个是需要身份验证的“真实”应用程序)。 “身份验证应用程序”返回 3 个 Set-Cookie
标头,我需要将它们添加到“真实”应用程序的请求标头中。但我不确定如何获取我能得到的那些标题(只有结果):
AuthenticationApplicationService.SoapClient authenticationSoapClient = new AuthenticationApplicationService.SoapClient("AuthenticationApplicationServiceSoap");
bool loggedInSuccess = await authenticationSoapClient.PerformLoginAsync();
// how do I get the cookie headers from this call and set them on the next?
RealService.SoapClient realSoapClient = new RealService.SoapClient("RealServiceSoap");
realSoapClient.PostAsync("hello");
对PerformLoginAsync
的第一次调用返回真或假以成功登录,并且标头包括Set-Cookie
。如何获取这些标头并将下一个请求中的 Cookie
标头设置为 PostAsync
?
如果还有其他问题,请告诉我!
【问题讨论】:
【参考方案1】:您应该使用 OperationContext,它具有可以发送 cookie 的属性。 要启用 cookie,您应该在绑定配置中将 allowcookie 属性设置为 true。
<bindings>
<basicHttpBinding>
<binding name="AuthSoap" allowCookies="true" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:63599/Auth" binding="basicHttpBinding"
bindingConfiguration="AuthSoap" contract="Auth.AuthSoap" name="AuthSoap" />
</client>
那么就可以如下调用登录方法了。
Auth.AuthSoapClient authSoapClient = new Auth.AuthSoapClient();
using (new OperationContextScope(authSoapClient.InnerChannel))
// please put the call of method in OperationContextScope
authSoapClient.Login("admin", "admin");
// the following code get the set-cookie header passed by server
HttpResponseMessageProperty response = (HttpResponseMessageProperty)
OperationContext.Current.IncomingMessageProperties[
HttpResponseMessageProperty.Name];
string header = response.Headers["Set-Cookie"];
// then you could save it some place
获得cookie后,每次调用方法时都应在标头中设置它。
Auth.AuthSoapClient authSoapClient = new Auth.AuthSoapClient();
using (new OperationContextScope(authSoapClient.InnerChannel))
//below code sends the cookie back to server
HttpRequestMessageProperty request = new HttpRequestMessageProperty();
request.Headers["Cookie"] = please get the cookie you stored when you successfully logged in
OperationContext.Current.OutgoingMessageProperties[
HttpRequestMessageProperty.Name] = request;
// please put the call of method in OperationContextScope
string msg = authSoapClient.GetMsg();
如果登录成功后每次都发送cookie很麻烦,可以考虑使用MessageInspector,参考链接最后一段代码 https://megakemp.com/2009/02/06/managing-shared-cookies-in-wcf/
【讨论】:
以上是关于如何在 WPF 应用程序中 SOAP 客户端的“Set-Cookie”标头响应的新请求中设置“Cookie”标头的主要内容,如果未能解决你的问题,请参考以下文章
elang(基于 yaws_soap_lib)soap 客户端的问题
随便聊聊 SOA & SOAP & WebService 的一些东西,以及客户端开发的代码逻辑解析
如何用 Delphi Win32 编写 SOAP 1.2 客户端的最佳方式