9

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 Answer 1

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

1 Comment

how to add multiple values in cookie? Like I referred this example to save user data like email id, user id and some other info in cookie.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.