ASP.NET Core 1.1 Hosting: Cookie Manager Wrapper In ASP.NET Core

In this article, you will learn how to work with cookies in an ASP.NET Core style (in the form of an interface), abstraction layer on top of cookie object and how to secure cookie data.
hflnet51
CookieManager is a .NET Core library to extend the cookie object and secure the data, which is encryped by the machine key, using “IDataProtector” dataprotector.

ICookieManager interface
Cookie Manager is an abstraction layer on top of ICookie Interface . This extends the Cookie behavior in terms of <TSource> generic support, Func<TResult>.This is implemented by DefaultCookieManager class . ICookie Interface is a depedenacy of this class. The list of APIs are given below in this interface.

 

ICookie Interface

ICookie Interface is an abstraction layer on top of http cookie object, which secures the data. This is implemented by HttpCookie class. The list of APIs available in this interface are given below.

 

Usages of CookieManager
Add CookieManager in startup Configure Service

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();

//add CookieManager
services.AddCookieManager();
}

Access the CookieManager API.

//Get or set <T>
//Cookieoption example
MyCookie myCook =  _cookieManager.GetOrSet<MyCookie>(“Key”, () =>
{
//write fucntion to store  output in cookie
return new MyCookie()
{
Id = Guid.NewGuid().ToString(),
Indentifier = “value here”,
Date = DateTime.Now
};

},new CookieOptions() { HttpOnly = true,Expires = DateTime.Now.AddDays(1) });

// expire time example
MyCookie myCookWithExpireTime = _cookieManager.GetOrSet<MyCookie>(“Key”, () =>
{
//write fucntion to store  output in cookie
return new MyCookie()
{
Id = Guid.NewGuid().ToString(),
Indentifier = “value here”,
Date = DateTime.Now
};

}, 60);

Source code is available on Github – https://github.com/nemi-chand/CookieManager

I hope, this wrapper helps you to play around with httpcookie in an ASP.NET Core. The source code is available for download at GitHub.