代码之家  ›  专栏  ›  技术社区  ›  Thomas

如何从WPF应用程序中的SOAP客户端的“set Cookie”头响应在新请求中设置“Cookie”头

  •  0
  • Thomas  · 技术社区  · 7 年前

    我正在将我的WPF应用程序与2个WCF应用程序集成(一个是“身份验证应用程序”,另一个是需要身份验证的“真实”应用程序)。“身份验证应用程序”返回3 Set-Cookie 头,我需要将它们添加到“real”应用程序的请求头中。但我不确定如何获取这些标题(仅结果):

    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,标头包括 设置Cookie . 如何获取这些标题并设置 Cookie PostAsync

    如果还有其他问题,请告诉我!

    1 回复  |  直到 7 年前
        1
  •  3
  •   Ackelry Xu    7 年前

    您应该使用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后,每次调用方法时都应该在标头中设置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();
            }
    

    https://megakemp.com/2009/02/06/managing-shared-cookies-in-wcf/