In this article I will explain with an example, how to use Browser Cookies in ASP.Net Core Razor Pages.
This article will also explain how to perform operations on Cookies i.e. reading values stored in Cookies, writing (saving) values in Cookies and also removing (deleting) Cookies in ASP.Net Core Razor Pages.
Note: For beginners in ASP.Net MVC Core Razor Pages, please refer my article ASP.Net Core Razor Pages: 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().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    services.AddHttpContextAccessor();
}
 
 
Namespaces
You will need to import the following namespace.
using Microsoft.AspNetCore.Http;
 
 
Razor PageModel (Code-Behind)
The IHttpContextAccessor is injected in the constructor of the IndexModel class 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 Razor Pages, please refer my article Using HttpContext in ASP.Net Core Razor Pages.
 
The PageModel consists of the following four Handler methods.
Handler method for handling GET operation
This Handler method is left empty as it is not required.
 
Handler method for writing Cookie
When the Write Cookie Button is clicked, WriteCookie Handler method is executed which saves the value of the Name TextBox to the Browser Cookie using the object of the CookieOptions class.
Finally, the Cookie is added to the Response.Cookies collection.
 
Handler method for reading Cookie
When the Read Cookie Button is clicked, ReadCookie Handler method is executed which fetches the Cookie value from the Request.Cookies collection using its Key.
The value is set in ViewData object, which is later displayed using JavaScript Alert Message Box.
 
Handler method for deleting Cookie
When the Remove Cookie Button is clicked, DeleteCookie Handler method is executed which deletes the Cookie from Browser using its Key.
public class IndexModel : PageModel
{
    private IHttpContextAccessor Accessor;
 
    public IndexModel(IHttpContextAccessor _accessor)
    {
        this.Accessor = _accessor;
    }
 
    public void OnGet()
    {
 
    }
 
    public void OnPostWriteCookie(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);
 
        RedirectToPage("/Index");
    }
 
    public void OnPostReadCookie()
    {
        //Fetch the Cookie value using its Key.
        string name = this.Accessor.HttpContext.Request.Cookies["Name"];
 
        ViewData["Message"] = name != null ? name : "undefined";
 
        RedirectToPage("/Index");
    }
 
    public void OnPostDeleteCookie()
    {
        //Delete the Cookie from Browser.
        Response.Cookies.Delete("Name");
 
        RedirectToPage("/Index");
    }
}
 
 
Razor Page (HTML)
The HTML of Razor Page consists of an HTML Form with a TextBox and three Submit Buttons i.e. for Reading Cookie, Writing Cookie and Deleting Cookie.
Each Submit Button has been set with the POST Handler method using the asp-page-handler attribute.
When the Read Cookie button is clicked, the value from the ViewData object is displayed using JavaScript Alert Message Box.
@page
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@model Cookies_Razor_Core.Pages.IndexModel
 
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <form method="post">
        <span>Name: </span><input type="text" id="txtName" name="name" /><br/><br/>
        <input type="submit" id="btnWrite" asp-page-handler="WriteCookie" value="Write Cookie" />
        <input type="submit" id="btnRead" asp-page-handler="ReadCookie" value="Read Cookie" />
        <input type="submit" id="btnDelete" asp-page-handler="DeleteCookie" value="Remove Cookie" />
        @if (ViewData["Message"] != null)
        {
            <script type="text/javascript">
                window.onload = function () {
                    alert('@ViewData["Message"]');
                };
            </script>
        }
    </form>
</body>
</html>
 
 
Screenshot
ASP.Net Core Razor Pages: Read, Write (Save) and Remove (Delete) Cookies
 
 
Downloads
Download Code