Techiehook Techiehook
Updated date Jul 23, 2024
In this article, we will discuss how to work with cookies in ASP.NET Core 8, including creating, reading, and deleting cookies.

What is a Cookie?

A cookie is a small piece of data or value that a website or server generates and sends to a user's web browser for future use. The browser stores this data and sends it back to the server or website with subsequent requests. Cookies are used to remember details about the user, such as login details, history of the user, language preference, and other details needed for the web application.

Working with Cookies in ASP.NET Core 8

In this article, we will see how to work with cookies in ASP.NET Core 8 which involves creating, reading, and deleting cookies. We can start with creating the cookies.

1. Creating Cookies

To create a cookie in ASP.NET Core 8, we can use the HttpContext.Response.Cookies.Append method. We can set various properties like the cookie's name, value, expiration time, etc as shown below.

public void SetCookie()
{
    var cookieOptions = new CookieOptions
    {
        // Set cookie to expire in 7 days
        Expires = DateTimeOffset.Now.AddDays(7), 
        // Cookie is essential for the application
        IsEssential = true,
        // Ensure the cookie is sent only over HTTPS
        Secure = true, 
        // Prevents client-side scripts from accessing the cookie
        HttpOnly = true, 
        // Controls when cookies are sent with cross-site requests
        SameSite = SameSiteMode.Strict 
    };

    Response.Cookies.Append("_WebsiteName", "TechieHook", cookieOptions);
}

2. Reading Cookies

To read a cookie, you use the HttpContext.Request.Cookies collection and pass the cookie name to get the correct cookie value.

public string GetCookie()
{
    if (Request.Cookies.TryGetValue("_WebsiteName", out var cookieValue))
    {
        return cookieValue;
    }

    return null; // Cookie not found
}

3. Deleting Cookies

To delete a cookie, we can set its expiration date to a past date using the HttpContext.Response.Cookies.Delete method. The cookie will be deleted after the expiration date.

public void DeleteCookie()
{
    Response.Cookies.Delete("_WebsiteName");
}

4. Middleware Configuration

We need to ensure that our application is properly configured to use cookies by setting up middleware in the Startup.cs file as shown below.

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Add services to the container
        services.AddControllersWithViews();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

5. Controller With Entire Code

Below is the sample controller that sets, gets, and deletes cookies.

using Microsoft.AspNetCore.Mvc;

public class CookieController : Controller
{
    public IActionResult Set()
    {
        var cookieOptions = new CookieOptions
        {
            Expires = DateTimeOffset.Now.AddDays(7),
            IsEssential = true,
            Secure = true,
            HttpOnly = true,
            SameSite = SameSiteMode.Strict
        };

        Response.Cookies.Append("_WebsiteName", "TechieHook", cookieOptions);
        return Content("Cookie has been set.");
    }

    public IActionResult Get()
    {
        if (Request.Cookies.TryGetValue("_WebsiteName", out var cookieValue))
        {
            return Content($"Cookie value: {cookieValue}");
        }

        return Content("Cookie not found.");
    }

    public IActionResult Delete()
    {
        Response.Cookies.Delete("_WebsiteName");
        return Content("Cookie has been deleted.");
    }
}

ABOUT THE AUTHOR

Techiehook
Techiehook
Admin, Australia

Welcome to TechieHook.com! We are all about tech, lifestyle, and more. As the site admin, I share articles on programming, tech trends, daily life, and reviews... For more detailed information, please check out the user profile

https://www.techiehook.com/profile/alagu-mano-sabari-m

Comments (0)

There are no comments. Be the first to comment!!!