How to use the cookie in the project asp.net mvc?
Loading
How to use the cookie in the project asp.net mvc?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Jignesh KumarPosted Aug 9, 2024, 4:08 AM
Hello Samia,
Working with ookies in MVC application,
How to set cookie :
How To Read Cookie :
How to delete cookie :
Mark TaborPosted Aug 10, 2024, 5:41 AM
hi you can set the cookie like this
public ActionResult SetCookie()
{
// Create a cookie with a name and value
HttpCookie myCookie = new HttpCookie("MyCookieName");
myCookie.Value = "MyCookieValue";
// Set the expiration date
myCookie.Expires = DateTime.Now.AddDays(1); // Cookie will expire in 1 day
// Add the cookie to the response
Response.Cookies.Add(myCookie);
return RedirectToAction("Index");
}
Read the cookie like this :
public ActionResult ReadCookie()
{
HttpCookie myCookie = Request.Cookies["MyCookieName"];
if (myCookie != null)
{
string cookieValue = myCookie.Value;
ViewBag.CookieValue = cookieValue;
}
else
{
ViewBag.CookieValue = "Cookie not found";
}
return View();
}
Delete the cookie like this :
public ActionResult DeleteCookie()
{
if (Request.Cookies["MyCookieName"] != null)
{
HttpCookie myCookie = new HttpCookie("MyCookieName");
myCookie.Expires = DateTime.Now.AddDays(-1); // Set the expiration date to the past
Response.Cookies.Add(myCookie);
}
return RedirectToAction("Index");
}
Tahir AnsariPosted Aug 8, 2024, 10:59 AM
To create and set a cookie, you'll typically use the
HttpResponseobject. You can do this in your controller action methodTo retrieve a cookie, use the
HttpRequestobjectTahir AnsariPosted Aug 8, 2024, 10:51 AM
Refer: https://www.aspsnippets.com/Articles/3373/ASPNet-MVC-Cookies-Read-Write-Save-and-Remove-Delete-Cookies-in-ASPNet-MVC/
https://stackoverflow.com/questions/39390240/create-cookie-asp-net-mvc