Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Distributed Session With ASP.NET Core and Couchbase

DZone's Guide to

Distributed Session With ASP.NET Core and Couchbase

Distributed Session extension for Couchbase is another handy tool in your box for helping you scale your ASP.NET Core applications.

· Database Zone
Free Resource

Traditional relational databases weren’t designed for today’s customers. Learn about the world’s first NoSQL Engagement Database purpose-built for the new era of customer experience.

Distributed Session is a way for you to store your session state outside of your ASP.NET Core application. Using Couchbase to store session state can help you when you need to scale your

You can follow along with the code samples I've created, available on GitHub.

Note that Couchbase.Extensions.Session is a beta release at the time of this writing.

Review of Session

Session state is simply a way to store data for a particular user. Typically, a token is stored in a user cookie and that token acts as a key to some set of data on the server side.

If you're familiar with ASP.NET or ASP Classic, this is done using Session. All the cookie work is done behind the scenes, so you simply use Session as a dictionary to store and retrieve whatever data you want.

if(Session["IsLoggedIn"] = false)
    Session["Username"] = "matt";

By default, in ASP.NET and ASP Classic, this information is stored in memory as part of the web application process.

In ASP.NET Core, you can also opt-in to this by configuring session with AddSession.

First, in Startup.cs, in the Configure function, tell ASP.NET Core to use session:

app.UseSession();

Then, in the ConfigureServices function, use AddSession to add a session provider service.

services.AddDistributedMemoryCache();
services.AddSession();

(This will use the default session settings; see the ASP.NET Core documentation for more information.)

Why Distributed Session?

However, if you are scaling out your web application with multiple web servers, you'll have to make some decisions about the session. If you continue to use in-process session, then you must configure sticky sessions (the first web server that a user hits is the one they will "stick" with for subsequent requests). This has some potential downsides (see this thread on ServerFault and this article on Microsoft's TechNet magazine).

If you don't want to use sticky sessions, then you can't use the in-process session option. You'll instead need to use a distributed session. There are a lot of options for where to put session data, but Couchbase's memory-first architecture and flexible scaling capabilities make it a good choice.

Using Distributed Session in ASP.NET Core

Before you start writing code, you’ll need a Couchbase Server cluster running with a bucket (I named mine sessionstore). You’ll also need to create a user with Data Reader and Data Writer permission on the bucket (I also called my user sessionstore just to keep things simple).

Adding Couchbase.Extensions.Session

Now, open up your ASP.NET Core application in Visual Studio. (I created a new ASP.NET Core MVC app, which you can find on GitHub). Next, with NuGet, install the Couchbase.Extensions.Session library. You have three options:

  1. Use the NuGet UI (see below)
  2. Install-Package Couchbase.Extensions.Session -Version 1.0.0-beta2 with the Package manager
  3. dotnet add package Couchbase.Extensions.Session --version 1.0.0-beta2 with the dotnet command line

Couchbase Extensions with NuGet

Configuring Couchbase

To configure the session provider, you’ll be writing some code that looks familiar if you’ve been following along in this Couchbase.Extensions series.

The ConfigureServices method in Startup.cs is where you’ll be adding configuration code.

First, use AddCouchbase, which is done with the Dependency Injection extension.

After that, set up the distributed cache for Couchbase with AddDistributedCouchbaseCache, which I covered in a blog post on distributed caching.

services.AddCouchbase(opt =>
{
    opt.Servers = new List<Uri> { new Uri("http://localhost:8091") };
});

services.AddDistributedCouchbaseCache("sessionstore", "password", opt => { });

Finally, configure Couchbase as a session store with AddCouchbaseSession.

services.AddCouchbaseSession(opt =>
{
    opt.CookieName = ".MyApp.Cookie";
    opt.IdleTimeout = new TimeSpan(0, 0, 20, 0);
});

You can configure the idle timeout (how long until the session expires after not being used), the cookie name, and more if you need to. In the above example, I set the timeout to 20 minutes and the cookie name to .MyApp.Cookie.

Writing to a Distributed Session

To access Session data, you can use HttpContext.Session.

First, I want to write something to session. In an About controller action, I used the SetObject method:

public IActionResult About()
{
    HttpContext.Session.SetObject("sessionkey", new
    {
        Name = "Matt",
        Twitter = "@mgroves",
        Guid = DateTime.Now
    });

    ViewData["Message"] = "I put a value in your session. Click 'Contact' to see it.";

    return View();
}

From this point on, whenever you click to view the About page, a new value will be stored in session with the key sessionkey. If you switch over to Couchbase Console, you can see the data being stored:

Distributed session document in Couchbase

Note that a user’s session is represented by a single document. So, if I were to insert another session value (as below), that value would be stored in the same document.

HttpContext.Session.SetObject("sessionkey2", new
{
    Address = "123 Main St",
    City = "Lancaster",
    State = "OH"
});

The resultant document would look like:

Two distributed session keys

You should be careful not to go crazy with the amount of data you put into session because Couchbase documents are limited to 20mb.

Reading From a Distributed Session

To get a value out of session, you can use GetObject and supply the session key. In the sample code, I did this in the Contact action:

public IActionResult Contact()
{
    ViewData["Message"] = HttpContext.Session.GetObject<dynamic>("sessionkey");

    return View();
}

After you visit the About page at least once, go to the Contact page. You should see the session object printed out on the page.

Output to ASP.NET from distributed session

That’s pretty much it. There are some other relatively self-evident methods available on Session. They are also outlined in the ASP.NET Core documentation.

One more thing: I named the cookie (.MyApp.Cookie). You can view this cookie in the browser of your choice. In Chrome, use Ctrl Shift I and navigate to the Application tab. You will see the cookie and its value.

Session cookie

You generally don’t need to know this detail in your day-to-day as an ASP.NET Core developer, but it’s good to know how things work just in case.

Summary

The distributed session extension for Couchbase is another tool in your box for helping to scale your ASP.NET Core applications. These handy .NET extensions help to demonstrate how Couchbase is the engagement database platform that you need.

If you have questions or comments on Couchbase Extensions, make sure to check out the GitHub repository or the Couchbase.NET SDK forums.

Learn how the world’s first NoSQL Engagement Database delivers unparalleled performance at any scale for customer experience innovation that never ends.

Topics:
database ,tutorial ,distributed session ,asp.net core ,couchbase

Published at DZone with permission of Matthew Groves, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}