在wcf服务中设置cookie

问题描述:

我有一个使用wcf rest服务的asp mvc应用程序(全部在同一个盒子上)。对于身份验证呼叫, 我正尝试在一个wcf rest服务中设置cookie。在客户端在wcf服务中设置cookie

码 -

 HttpResponseMessage resp; 
     HttpClient client = new HttpClient("http://localhost/auth/login/"); 
     resp = client.Get(); 

在web服务我只是用FormsAuthentication设置一个authcookie。

 HttpCookie authCookie = FormsAuthentication.GetAuthCookie("foo", false); 
     HttpContext.Current.Response.Cookies.Add(authCookie); 

假设凭据是硬编码的代码 - 如果我物理导航到browserpage

 http://localhost/auth/login 

(代码中的硬编码的凭据),我可以看到的是,身份验证cookie被设置。但是,如果我只是通过代码调用它(如上所示),则不会设置身份验证cookie。

有什么明显的,我在这里俯瞰?

当您以编程方式调用WCF服务时,它设置的cookie存储在HttpClient实例中。客户端浏览器从不会看到它,所以它永远不会被设置在它内部。所以你需要手动设置:

using (var client = new HttpClient("http://localhost/auth/login/")) 
{ 
    var resp = client.Get(); 
    // Once you get the response from the remote service loop 
    // through all the cookies and append them to the response 
    // so that they are stored within the client browser. 
    // In this collection you will get all Set-Cookie headers 
    // sent by the service, so find the one you need and set it: 
    foreach (var cookie in result.Headers.SetCookie) 
    { 
     // the name of the cookie must match the name of the authentication 
     // cookie as you set it in your web.config. 
     var data = cookie["SomeCookieName"]; 
     Response.AppendCookie(new HttpCookie("SomeCookieName", data)); 
    } 
} 
+0

谢谢达林。这工作。将.aspxauth cookie的名称更改为服务器中的其他名称导致它不能设置,但这是另一个问题... :) – user275157 2011-03-29 16:55:03