Laziale
Laziale

Reputation: 8225

Setting and getting cookies in asp.net mvc4

I'm trying to set and get cookies in a project I'm working on in asp.net mvc4.

This is how I'm setting the cookies:

                    var Username = new HttpCookie("Username");
                    Username.Value = model.UserName;
                    Username.Expires = DateTime.Now.AddDays(7);
                    Username.Secure = true;
                    Response.Cookies.Add(Username);

Then, in other controller action, I'm trying this:

HttpCookie cookie = Request.Cookies["Username"];

but I'm getting null for that specific cookie. Also, I don't know if that would make a difference but I'm not requesting the cookie in the action in which this current action redirects but in other action. That shouldn't make difference since I'm setting the expiration date +7 days from the creation date.

Upvotes: 6

Views: 6379

Answers (1)

Dipal Mehta
Dipal Mehta

Reputation: 462

Laziale,

Your code is perfectly Ok.

This is only due to fact that your cookie is secure.

 Username.Secure = true;

It does not sent back due to that reason only. Try remove that line. It shown perfectly in Request.Cookie collection

Hope helps.

Upvotes: 3

Related Questions