在WCF服务中设置Cookie [英] setting cookies within a wcf service

查看:139
本文介绍了在WCF服务中设置Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a asp mvc application consuming wcf rest services (all on the same box). For authentication calls, I am trying to set cookies inside a wcf rest service.

客户端代码-

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

在Web服务中,我仅使用FormsAuthentication设置authcookie.

In the webservice I just use FormsAuthentication to set an authcookie.

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

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

Assuming the credentials are hardcoded in the code - If I physically navigate to the browserpage

       http://localhost/auth/login 

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

(hard code credentials in the code) I can see that the authentication cookie is being set. However, if I just invoke it through code (as shown above) the authentication cookie is not being set.

有什么明显的地方让我忽略了吗?

Is there something obvious that I am overlooking here?

推荐答案

以编程方式调用WCF服务时,其设置的cookie存储在HttpClient实例中.客户端浏览器永远不会看到它,因此它永远都不会在其中设置.因此,您需要手动进行设置:

When you call the WCF service programatically the cookie it sets is stored in the HttpClient instance. The client browser never sees it so it is never set inside it. So you will need to set it manually:

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));
    }
}

这篇关于在WCF服务中设置Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆