setting cookies within a wcf service

2019-06-10 08:33发布

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条回答
Melony?
2楼-- · 2019-06-10 09:05

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));
    }
}
查看更多
登录 后发表回答