In this article I will explain with an example, how to read, write and remove (Delete)
Cookies in ASP.Net Core (.Net Core 8) Razor Pages.
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.AddMvc();
builder.Services.AddHttpContextAccessor();
var app = builder.Build();
//Configure Routes
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
app.Run();
Namespaces
You will need to import the following namespace.
using Microsoft.AspNetCore.Mvc.RazorPages;
RazorPageModel (Code-Behind)
The PageModel consists of the following 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)
HTML Markup
The HTML of Razor Page consists of an HTML Form.
Inside the HTML Form, there is an HTML INPUT TextBox and three Submit Button for Reading, Writing 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
@model Cookies_Razor_Core.Pages.IndexModel
@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">
<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
Downloads