Creating and accessing Cookies in ASP.NET MVC3

2019-02-02 16:12发布

问题:

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.

回答1:

....    
//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;
....