0

我有一个使用 wcf 休息服务的 asp mvc 应用程序(都在同一个盒子上)。对于身份验证调用,我正在尝试在 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);

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

       http://localhost/auth/login 

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

我在这里忽略了什么明显的东西吗?

4

1 回答 1

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));
    }
}
于 2011-03-28T20:06:15.010 回答