我正在将我的 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
的第一次调用返回 true 或 false 表示已成功登录,并且标头提示Set-Cookie
。如何获取这些标头并在下一个请求PostAsync
时设置Cookie
标头?
如果还有其他问题,请告诉我!
你应该使用 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/