In this article we will learn about How to use cookies in ASP.Net Core. In this section, we will go over how to use ASP.Net Core MVC to read the values stored in Cookies, write (save) values in Cookies, and remove (delete) Cookies. Please read my previous article about Building CRUD REST APIs in ASP.Net Core 7.0 with EF.
What are Cookies?
A cookie is a small bit of text that accompanies requests and pages as they go between the Web server and browser. The cookie contains information the Web application can read whenever the user visits the site.
- Specific cookies known as HTTP cookies are used to identify specific users and improve your web browsing experience.
- Data stored in a cookie is created by the server upon your connection. This data is labeled with an ID unique to you and your computer.
- When the cookie is exchanged between your computer and the network server, the server reads the ID and knows what information to specifically serve to you.
Prerequisite
Here I have used the below configuration.
– Visual Studio 2022
– .NET 7 SDK
Creating an ASP.Net Core Web Application
- Launch the Visual Studio IDE and click on “Create new project”.
- In the “Create new project” window, select “
ASP.NET Core Web App(Model-View-Controller)
” from the list of templates displayed. - Click Next. In the “Configure your new project” window, specify the name and location for the new project and then click Create.
- In the “Create New ASP.NET Core Web Application” window shown next, select .NET Core as the runtime and
.NET 7.0
from the drop-down list at the top. Select “API” as the project template to create a new ASP.NET Core API application. - Ensure that the check boxes “Enable Docker Support” is disabled s we won’t be using those features here and “Configure for HTTPS” are checked.
- Ensure that Authentication is set as “No Authentication” as we won’t be using authentication either and Click Create.
Adding the HttpContextAccessor Configuration
To add the HttpContextAccessor
, open the program.cs
file and the build line to register in the services.
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddHttpContextAccessor();
Adding the Read/Write/Delete operation on the Controller
- The
IHttpContextAccessor
is injected in the Controller and assigned to the private property Accessor and later used to access the HttpContext property. - Action method for Adding Cookie – When the Write Cookie Button is clicked, AddCookie 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 readonly ILogger<HomeController> _logger;
private IHttpContextAccessor Accessor;
public HomeController(ILogger<HomeController> logger, IHttpContextAccessor _accessor)
{
_logger = logger;
this.Accessor = _accessor;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult AddCookie(string name)
{
if (name != null)
{
//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);
}
TempData["Message"] = name != null ? name : "undefined";
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");
}
}
Modifying the Template 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
asp-action
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 in the label.
<div class="text-center">
<div class="panel panel-default">
<div class="panel-body">Cookies in ASP.Net Core MVC- Complete Guide
<div class="col-sm-6 mt-5">
<form asp-controller="Home" method="post">
<input type="text" name="name" id="txt_cookies" class="form-control" placeholder="Enter cookie here" autocomplete="off"/>
@*Buutons that take into Actions*@
<div class="mt-2">
<input type="submit" id="btnWrite" asp-action="AddCookie" value="Write Cookie" class="btn btn-success" />
<input type="submit" id="btnRead" asp-action="ReadCookie" value="Read Cookie" class="btn btn-primary" />
<input type="submit" id="btnDelete" asp-action="DeleteCookie" value="Remove Cookie" class="btn btn-danger" />
</div>
<div class="mt-4 ml-5" style="border: 1px solid #ffc107;">
The Coookie result dispaly here:
@if (TempData["Message"] != null)
{
<strong><label id="lbl_result" style="color: red;">@TempData["Message"]</label></strong>
}
</div>
</form>
</div>
</div>
</div>
</div>
That’s it. Now run the application and we can see the output like below how the cookies works.
What are HTTP Cookies and why do we need them?
HTTP cookies, or internet cookies, are built specifically for Internet web browsers to track, personalize, and save information about each user’s session. A “session” just refers to the time you spend on a site.
Cookies are created to identify you when you visit a new website. The web server — which stores the website’s data — sends a short stream of identifying info to your web browser.
Browser cookies are identified and read by “name-value” pairs. These tell cookies where to be sent and what data to recall.
What Are Cookies Used For?
Websites use HTTP cookies to streamline your web experiences. Without cookies, you’d have to login again after you leave a site or rebuild your shopping cart if you accidentally close the page. Making cookies an important a part of the internet experience.
Based on this, you’ll want to understand why they’re worth keeping — and when they’re not.
Here’s how cookie are intended to be used:
- Session management– For example, cookies let websites recognize users and recall their individual login information and preferences, such as sports news versus politics.
- Personalization– Customized advertising is the main way cookies are used to personalize your sessions. You may view certain items or parts of a site, and cookies use this data to help build targeted ads that you might enjoy.
- Tracking– Shopping sites use cookies to track items users previously viewed, allowing the sites to suggest other goods they might like and keep items in shopping carts while they continue shopping.
What are the different types of HTTP Cookies?
With a few variations, cookies in the cyber world come in two types: session and persistent.
Session cookies are used only while navigating a website. They are stored in random access memory and are never written to the hard drive.
When the session ends, session cookies are automatically deleted. They also help the “back” button or third-party anonymizer plugins work. These plugins are designed for specific browsers to work and help maintain user privacy.
Persistent cookies remain on a computer indefinitely, although many include an expiration date and are automatically removed when that date is reached.
Persistent cookies are used for two primary purposes:
- Authentication– These cookies track whether a user is logged in and under what name. They also streamline login information, so users don’t have to remember site passwords.
- Tracking– These cookies track multiple visits to the same site over time. Some online merchants, for example, use cookies to track visits from particular users, including the pages and products viewed. The information they gain allows them to suggest other items that might interest visitors. Gradually, a profile is built based on a user’s browsing history on that site.
Why Cookies Can Be Dangerous?
Since the data in cookies doesn’t change, cookies themselves aren’t harmful. They can’t infect computers with viruses or other malware. However, some cyberattacks can hijack cookies and enable access to your browsing sessions.
Conclusion
This article explained about How to use cookies in ASP.Net Core. We will cover how to use ASP.Net Core MVC to read the values stored in Cookies, write (save) values in Cookies, and remove (delete) Cookies.
Leave behind your valuable queries and suggestions in the comment section below. Also, if you think this article helps you, do not forget to share this with your developer community. Happy Coding 🙂
Related Articles
- How to Integrate AdminLTE with ASP.NET Core
- How to run ASP.Net Core Web Application in Docker Container
- ChatGPT Integration in ASP.Net Core using OpenAI
- How to use cookies in ASP.Net Core- Complete Guide
- Deploy ASP.Net Core apps to Azure App Service
- How to detect whether page is load on Mobile or Desktop browser in ASP.Net Core
- AddTransient Vs AddScoped Vs AddSingleton Example in ASP.Net Core
- Razor file compilation in ASP.NET Core
- ViewData in ASP.Net Core MVC
- How controller finds a view (View Discovery)
Jayant Tripathy
Coder, Blogger, YouTuberA passionate developer keep focus on learning and working on new technology.
I am curious, you used builder.Services.AddHttpContextAccessor(); and then you have the service injected into the Controller. Is this another way of making DI.
Because I have seen so far only this way –
builder.Services.AddSingleton();
Thank you.
builder.Services.AddSingleton lt IHttpContextAccessor, HttpContextAccessor gt();
Somehow this line got edited. I guess the lt and gt signs are the reason. If this happens again consider the above.
HttpContextAccessor is default as singleton and is designed to be used as a singleton, can be used by services that are singletons so there is no need to externally through AddSingleton(). Please see below link for more details
https://learn.microsoft.com/en-us/answers/questions/821735/are-there-any-risks-to-injecting-ihttpcontextacces
Great article! The step-by-step explanation on how to use cookies in ASP.NET Core was extremely helpful. I appreciate the clear instructions and the code snippets provided, which made it easy to understand and implement cookies in my projects. Thank you for sharing this valuable tutorial, it was exactly what I was looking for! Keep up the great work.
-GPTOnline