setting cookies within a wcf service

☆樱花仙子☆ 提交于 2020-05-14 09:01:32

问题


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.

Code on the client side -

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

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 

(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?


回答1:


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


来源:https://stackoverflow.com/questions/5463431/setting-cookies-within-a-wcf-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!