在wcf服务中设置cookie

时间:2011-03-28 18:32:47

标签: asp.net-mvc wcf wcf-security wcf-rest webhttpbinding

我有一个使用wcf休息服务的asp mvc应用程序(全部在同一个盒子上)。对于身份验证调用 我想在wcf休息服务中设置cookie。

客户端代码 -

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

在webservice中,我只使用FormsAuthentication来设置authcookie。

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

假设凭证在代码中是硬编码的 - 如果我实际导航到浏览器页面

       http://localhost/auth/login 

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

有什么明显的东西我在这里俯瞰吗?

1 个答案:

答案 0 :(得分:1)

当您以编程方式调用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));
    }
}
相关问题