.NET Core

How To Use Cookies In .NET Core

Introduction

In this article, we will learn how to use Cookies in our .NET Core Web applications. I assume that your web application is already created.

Prerequisite

  • .NET Core SDK
  • Visual Studio

In ASP.NET MVC, we accessed cookies from httpcontext but in .NET Core, we need to use IHttpContextAccessor interface which falls under “Microsoft.AspNetCore.Http” namespace

Now, We can use the cookies by following the below codes.

First, we need to add an IHttpContextAccessor in the ConfigureServices method of Startup class.

services.AddHttpContextAccessor();

To Set Cookie

CookieOptions option = new CookieOptions
{
   Expires = DateTime.Now.AddMinutes(1)
};
   Response.Cookies.Append("Key Name", "Value", option);

To Get/Read Cookie

We can get/read cookies in two ways

  1. Read from the Request object.
    var cookieValue = Request.Cookies["Key Name"];
  2. Read from IHttpContextAccessor.
    private readonly IHttpContextAccessor _httpContextAccessor;
    
    public HomeController(IHttpContextAccessor httpContextAccessor)
    {
      this._httpContextAccessor = httpContextAccessor;    
    }
    
    var value = _httpContextAccessor.HttpContext.Request.Cookies["Key Name"];
    
    
    

Below are available Cookie Options:

  1. Domain – The domain you want to associate with a cookie
  2. Path – Path of Cookie
  3. Expires – The termination date and time of the cookie
  4. HttpOnly – Indicates whether a cookie is accessible by client-side script or not.
  5. Secure – Send the cookie using Secure Sockets Layer (SSL) that is, over HTTPS only.

Hire .NET Developers in India with sufficient experience to give world-class services to support and manage your web and mobile application. Hire our Dedicated ASP.NET Developers & programmers for cost-effective and all-inclusive solutions for boosting your business’s growth if you need excellent consulting services for creating dynamic web apps using ASP.NET.

Faisal Pathan

Faisal Pathan is a founder of TheCodeHubs, .NET Project Manager/Team Leader, and C# Corner MVP. He has extensive experience with designing and developing enterprise-scale applications. He has good skills in ASP.NET C#, ASP.NET Core, ASP.NET MVC, AngularJS, Angular, React, NodeJS, Amazon S3, Web API, EPPlus, Amazon MWS, eBay Integration, SQL, Entity Framework, JavaScript, eCommerce Integration like Walmart, Tanga, Newegg, Group-on Store, etc. and Windows services.

View Comments

Share
Published by
Faisal Pathan

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

2 years ago