In this article I will explain with an example, what are Cookies and how to use it in ASP.Net Core.
 
 
 

Program class Configuration

Inside the Program.cs file, the IHttpContextAccessor interface service is added to the builder object using the AddHttpContextAccessor method.
var builder = WebApplication.CreateBuilder(args);
 
//Enabling MVC
builder.Services.AddControllersWithViews();
builder.Services.AddHttpContextAccessor();
var app = builder.Build();
 
//Configuring Routes
app.MapControllerRoute(
     name: "default",
     pattern: "{controller=Home}/{action=Index}/{id?}");
 
app.Run();
 
 

Namespaces

You will need to import the following namespace.
using Microsoft.AspNetCore.Mvc;
 
 

Controller

The Controller consists of the following Action methods.

Action method for handling GET operation

Inside this Action method, simple the View is returned.
 

Action method for writing Cookie

When the Write Cookie Button is clicked, WriteCookie Action method is executed.
Then, the Expiry Date of the Cookie is set using the CookieOptions class.
Finally, the Cookie is added to the Response.Cookies collection and the page is redirected to itself.
 

Action method for reading Cookie

When the Read Cookie Button is clicked, the Cookie value is read from the Request.Cookies collection using its Key and saved into a TempData object.
The value read from the Cookie is set in TempData object and the page is redirected to itself.
 

Action method for deleting Cookie

When the Remove Cookie Button is clicked, the Cookie value is read from the Request.Cookies collection using its Key and is removed or deleted.
Finally, the Cookie is updated back into the Response.Cookies collection and the page is redirected to itself.
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.
@addTagHelper*,Microsoft.AspNetCore.Mvc.TagHelpers
@{
     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: What are Cookies and how to use it
 
 

Downloads