In this article I will explain with an example, how to use Browser Cookies in ASP.Net Core MVC.
This article will illustrate how to perform following operations on Cookies i.e. reading values stored in Cookies, writing (saving) values in Cookies and also removing (deleting) Cookies in ASP.Net Core MVC.
Note: For beginners in ASP.Net MVC Core, please refer my article ASP.Net MVC Core Hello World Tutorial with Sample Program example.
 
 
Startup class Configuration
You will need to configure the AddHttpContextAccessor function in the ConfigureServices method of Startup class as shown below.
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddHttpContextAccessor();
}
 
 

Namespaces
You will need to import the following namespace.
using Microsoft.AspNetCore.Http;
 
 
Controller
The IHttpContextAccessor is injected in the Controller and assigned to the private property Accessor and later used to access the HttpContext property.
Note: For more details on using HttpContext property in ASP.Net Core, please refer my article Using HttpContext in ASP.Net Core.
 
The Controller consists of the following four Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
 
Action method for writing Cookie
When the Write Cookie Button is clicked, WriteCookie Action method is executed.
First, the Expiry Date of the Cookie is set using the CookieOptions class.
And then, the Cookie is added to the Response.Cookies collection using the Append method which accepts, the name of the Cookie, its value and the CookieOptions class object as parameters.
 
Action method for reading Cookie
When the Read Cookie Button is clicked, ReadCookie Action method is executed which fetches the Cookie value from the Request.Cookies collection using its Key.
The read value of the Cookie is set in TempData object, which is later displayed using JavaScript Alert Message Box.
 
Action method for deleting Cookie
When the Remove Cookie Button is clicked, DeleteCookie Action method is executed which removes the Cookie from Request.Cookies collection using the Delete method.
public class HomeController : Controller
{
    private IHttpContextAccessor Accessor;
 
    public HomeController(IHttpContextAccessor _accessor)
    {
        this.Accessor = _accessor;
    }
 
    public IActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public IActionResult WriteCookie(string name)
    {
        //Set the Expiry date of the Cookie.
        CookieOptions option = new CookieOptions();
        option.Expires = DateTime.Now.AddDays(30);
 
        //Create a Cookie with a suitable Key and add the Cookie to Browser.
        Response.Cookies.Append("Name", name, option);
 
        return RedirectToAction("Index");
    }
 
    [HttpPost]
    public IActionResult ReadCookie()
    {
        //Fetch the Cookie value using its Key.
        string name = this.Accessor.HttpContext.Request.Cookies["Name"];
 
        TempData["Message"] = name != null ? name : "undefined";
 
        return RedirectToAction("Index");
    }
 
    [HttpPost]
    public IActionResult DeleteCookie()
    {
        //Delete the Cookie from Browser.
        Response.Cookies.Delete("Name");
 
        return RedirectToAction("Index");
    }
}
 
 
View
The View consists of an HTML Form with following ASP.Net Tag Helpers attributes.
asp-controller – Name of the Controller. In this case the name is Home.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The Form consists of a TextBox and three Submit Buttons i.e. for Reading Cookie, Writing Cookie and Deleting Cookie.
Each Submit Button has been set with a FormAction attribute which specifies the Action method which will be called when the Submit Button is clicked.
When the Read Cookie button is clicked, the value from the TempData object is displayed using JavaScript Alert Message Box.
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <form method="post" asp-controller="Home">
        <span>Name: </span><input type="text" id="txtName" name="name" /><br/><br/>
        <input type="submit" id="btnWrite" formaction="@Url.Action("WriteCookie")" value="Write Cookie"/>
        <input type="submit" id="btnRead" formaction="@Url.Action("ReadCookie")" value="Read Cookie"/>
        <input type="submit" id="btnDelete" formaction="@Url.Action("DeleteCookie")" value="Remove Cookie"/>
    </form>
    @if (TempData["Message"] != null)
    {
        <script type="text/javascript">
            window.onload = function () {
                alert('@TempData["Message"]');
            };
        </script>
    }
</body>
</html>
 
 
Screenshot
ASP.Net Core Cookies: Read, Write (Save) and Remove (Delete) Cookies in ASP.Net Core MVC
 
 
Downloads