简体   繁体   中英

Send Cookie in Post Response WebAPI

I am trying to send the user a cookie after I authenticate him. everything works perfect, the response is being constructed in my code, but even after the client got the response, There is no cookie saved in the browser (checking it via chrome F12 -> Resources).

Note: I can see the response being sent in fiddler with my cookie :

在此处输入图片说明

I wonder what is going wrong and why the browser doesn't save the cookie.

Here is the WebAPI function that handles the Post request:

public HttpResponseMessage Post([FromBody]User user)
        {
            IDal dal = new ProGamersDal();
            var currentUser = dal.GetUser(user.Username, user.Password);

            if (currentUser == null)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Bad request.");
            }
            else
            {
                var res = new HttpResponseMessage();
                var cookie = new CookieHeaderValue("user",JsonConvert.SerializeObject(new ReponseUser(){username = currentUser.Username, role = currentUser.Role}));
                cookie.Expires = DateTimeOffset.Now.AddDays(1);
                cookie.Domain = Request.RequestUri.Host;
                cookie.Path = "/";

                res.Headers.AddCookies(new CookieHeaderValue[] { cookie });
                return res;
            }
        }

I've found out what the problem is since in Firefox the cookie was saved.

In chrome you cannot set a cookie with the domain of 'localhost' since it is considered as invalid domain (valid domain must contain two dots in it) - and therefore the cookie is invalid.

In order to solve it, in case of localhost, you should either:

  1. set the domain to null.
  2. set the domain to '' (empty)
  3. set the domain to '127.0.0.1'

This is the fix in my code:

cookie.Domain = Request.RequestUri.Host == "localhost" ? null : Request.RequestUri.Host;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM