【问题标题】:setting cookies within a wcf service在 wcf 服务中设置 cookie
【发布时间】:2011-03-28 18:32:46
【问题描述】:

我有一个使用 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。

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

【问题讨论】:

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


    【解决方案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));
        }
    }
    

    【讨论】:

    • 谢谢达林。那行得通。将 .aspxauth cookie 的名称更改为服务器中的其他名称会导致未设置它,但这是另一个问题...:)
    猜你喜欢
    • 2012-11-18
    • 1970-01-01
    • 1970-01-01
    • 2014-12-11
    • 2015-06-23
    • 1970-01-01
    • 2013-05-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多