Creating Cookie in ASP.NET MVC Action | Handling Cookies in ASP.NET MVC | Set Cookie Expiry in ASP.NET MVC | ASP.NET MVC Tutorial

We can create Cookie and set value to it in ASP.NET MVC Action method using the HttpCookie object using System.Web namespace. This created cookie should be added to HttpResponse object before returning the view in ASP.NET MVC Action method.

Below sample C# code demonstrated on how to create and set cookie in ASP.NET MVC Action method and pass it to Razor:

public ActionResult Index()
   HttpCookie cookie = new HttpCookie("cookie_name","cookie_value");
   cookie.Expires = DateTime.Now.AddDays(1);
   return View();
In detail:

To get a cookie:
HttpCookie cookie = HttpContext.Request.Cookies.Get("cookie_name");
To check for a cookie's existence:
HttpContext.Request.Cookies["cookie_name"] != null
To save a cookie:
HttpCookie cookie = new HttpCookie("cookie_name");
HttpContext.Response.SetCookie(cookie );