How to manage state in Dotnet core web API

Introduction to problem statement

For some cases it is required to maintain state in Web-API. But as per design principles, it is not a good practice to make a restful API stateful. In modern backend development, APIs are created as stateless because it makes API highly distributed and scalable. Restful WebAPIs are usually stateless as servers don't require state of the services.

Let's explore the below details regarding - "How to manage state in Dotnet core web API" if in some rare cases we need to manage state in restful Web API in .NET Core.

Possible Solutions

1. Session

Session is the technique to store temp data for particular time period. To use this, you need to add nudget package "Microsoft.AspNetCore.Session" as shown in below screenshot:

Now open the startup class and include "AddSession" & "AddDistributedMemoryCache" inside ConfigureServices method as below:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddDistributedMemoryCache();
    services.AddSession(options =>
    {
        options.IdleTimeout = TimeSpan.FromMinutes(1); // session timeout can be set here ...
    });
}

Include session in middleware as below:

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
 {
     if (env.IsDevelopment())
     {
         app.UseDeveloperExceptionPage();
     }

     app.UseRouting();
     app.UseAuthorization();
     app.UseSession();
     app.UseEndpoints(endpoints =>
     {
         endpoints.MapControllers();
     });
 }

And that's it. We can now utilize session objects in our controller classes or wherever that is required in API.

[HttpGet, Route("name")]
public string GetName(string name)
{
    // Set the name into session ...
    HttpContext.Session.SetString("name", name);

    // Get the name from session and return back ...
    return HttpContext.Session.GetString("name");
}

Now run the API and test the code:

2. Cookies

Http cookies is state management technique that is used to set & get small piece of data on web pages or APIs. Cookies stores data in Key-value pair. If we use cookies in right way, it can boost performance of our application / API.

To write & read a cookie in dotnet core, below is the simple code snippet:

[HttpGet, Route("cookies")]
public string CookiesTest(string value)
{
    // Set the value into session ...
    CookieOptions option = new CookieOptions();
    option.Expires = DateTime.Now.AddMilliseconds(10);
    // store data in key/ value pair ...
    Response.Cookies.Append("key", value, option);

    // Get the value from session and return back ...
    return Request.Cookies["key"];
}

If you want to delete cookie, use below code:

Response.Cookies.Delete("Key_Name");

3. Distributed Cache

We can also implement Distributed Cache technique for state management. This cache is really good because this is stored at central level and access to this cache objects is very fast. It cut down the complexity of distributed servers as it does not require affinity with particular server from where data is stored. So in sort, data can be stored by any of the distributed servers.

We have below four methods to preform operation in distributed cache mechanism:

  1. GetAsync: used to get data from cache

  2. SetAsync: used to set data in cache

  3. RemoveAsync: used to remove data from cache

  4. RefreshAsync: used to refresh data in cache

For more details please check the Microsoft documentation for building distributed cache system.

Conclusion:

It is highly advised that our web APIs should be stateless, specially RESTFul services. Incase of any urgent state mechanism requirement, we should opt for distributed cache mechanism in our Web APIs. Now a days, with modern web infrastructure, it is more convenient to maintain centralized caches for such requirements. 'Redis' cache is the best example of this, which can make the API performance really fast.

Did you find this article valuable?

Support Priyesh Singh by becoming a sponsor. Any amount is appreciated!