Zabady
Zabady

Reputation: 301

Creating and accessing Cookies in ASP.NET MVC3

How can I create cookies in the controller and access it in any view just like for example

User.Identity.Name

I can use that code anywhere since the user has logged in and it's also removed when the user log out based on the default code of

FormsAuthentication.SetAuthCookie

Also I want to know how to delete or clear that cookie.

Upvotes: 9

Views: 13947

Answers (1)

user1263800
user1263800

Reputation:

....    
//create cookie
var cookie = new HttpCookie("cookieName");

cookie.Value = "value";
Response.Cookies.Add(cookie);

//remove cookie
var cookie = new HttpCookie("cookieName");
cookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(cookie);

//To Request the cookies value
var val = Request.Cookies["cookieName"].Value;
....

Upvotes: 25

Related Questions