0

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:

enter image description here

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; } } 
2
  • Your image shows the "Request" headers... What values are in the "Response" headers? Commented Sep 23, 2013 at 11:52
  • The request header contains the cookie as well Commented Sep 23, 2013 at 16:05

1 Answer 1

3

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; 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.