Skip to main content

Posts tagged with 'ASP.NET'

This is a repost that originally appeared on the Couchbase Blog: Geospatial Search with ASP.NET Core, Aurelia, and Google Maps.

Geospatial search is now fully supported in Couchbase Server 5.5. Check out the Couchbase Server 5.5 announcement, and download the developer build for free right now.

In this post, I’m going to demonstrate the geospatial search capabilities of Couchbase Full Text Search by creating a web-based UI that performs searches. Whenever I think of geospatial searches, I think about Yelp, which is great at helping me find restaurants in a specific area.

So I’m going to have a little fun and create a very bare-bones version of Yelp, but only for hotels.

If you want to follow along, the full source code is available on Github.

Getting set up

Here are the steps I took to create a new project before I started writing code.

  1. At the command line: dotnet new aurelia. This assumes that you have .NET Core installed. Note that Geospatial Search is not a .NET-only feature: you can use it with the other Couchbase SDKs like Node.js, Java, etc. It also assumes that you’ve installed a SPA template for Aurelia. You can also go with Angular or React if you’d like, but I really like Aurelia, and I think you should give it a chance.

  2. The above command will create a shell of an ASP.NET Core project. In this blog post, I’m not going to use Razor. I’m just using ASP.NET as a backend for REST API endpoints.

  3. npm install aurelia-google-maps. You don’t have to use this, but the aurelia-google-maps plugin will make it easy for me to interact with Google Maps in my app.

  4. I opened this project in Visual Studio 2017. I added Couchbase.Extensions.DependencyInjection with NuGet. You don’t have to use this extension but it makes things easier.

  5. I installed Couchbase Server 5.5, including the Full Text Search service. I setup the travel-sample bucket. I created a user "matt" with full access to that bucket.

Create a Geospatial Index

Before building the ASP.NET backend, we need to create a geospatial index in Couchbase Server. Once you log in, click "Search" on the menu (it’s under "Workbench"). Click "Add Index" to get started.

Create Geospatial index

I named my index "mygeoindex". I selected travel-sample as the bucket to index.

In "Type Mappings", I uncheck the default. I add a new type mapping with a type name of "hotel". Every hotel document in "travel-sample" has a type with a value of "hotel". Check the "only index specified fields" box.

I’m going to add two child fields. One is "geo", which contains the geospatial coordinates inside a hotel document. Make sure to select "geopoint" as the type. The other is "name", which will be the name of the hotel. I choose to "store" each of these: it will make the index larger, but I can avoid a secondary lookup if I store the information in the index.

Important Note: There is a bug (NCBC-1651) in the current release of the .NET SDK that will cause an error if you try to read from a geopoint field. In the code samples, I’ve created a workaround: I don’t actually get the geo & name fields from the search index. I instead use the document key returned by search to make a secondary "get" call and get the full document. Keep in mind this is still a technique you may want to consider if you want to keep the size of your index down. This bug has already been fixed and will be in a future release. Such is the peril of being on the cutting edge!

That’s all there is to it. Click "Create Index". Watch the "indexing progress" on the next screen until it gets to 100% (it should not take very long, assuming you remembered to uncheck "default").

ASP.NET Core REST Endpoints

Next, let’s move over to ASP.NET. I’ll create two endpoints. One endpoint will demonstrate the bounding box search method, and the other will demonstrate the distance search method.

I’ll need a Couchbase bucket object to execute the queries. Follow the examples in my blog post about dependency injection or check out the source code on Github if you’ve never done this before.

Bounding Box

A "bounding box" search means that you define a box on a map, and you want to search for points of interest that are inside of that box. You only need two points to define a box: the top right corner coordinates and the bottom left corner coordinates. (Coordinates are latitude and longitude).

public class BoxSearch
{
    public double LatitudeTopLeft { get; set; }
    public double LongitudeTopLeft { get; set; }
    public double LatitudeBottomRight { get; set; }
    public double LongitudeBottomRight { get; set; }
}

To create a bounding box geospatial query, use the GeoBoundingBoxQuery class available in the .NET SDK. I’ll do this inside of a POST method with the above BoxSearch class as a parameter.

        [Route("api/Box")]
        [HttpPost]
        public IActionResult Box([FromBody] BoxSearch box)
        {
            var query = new GeoBoundingBoxQuery();
            query.TopLeft(box.LongitudeTopLeft, box.LatitudeTopLeft);
            query.BottomRight(box.LongitudeBottomRight, box.LatitudeBottomRight);
            var searchParams = new SearchParams()
                // .Fields("geo", "name") // omitting because of bug NCBC-1651
                .Limit(10)
                .Timeout(TimeSpan.FromMilliseconds(10000));
            var searchQuery = new SearchQuery
            {
                Query = query,
                Index = "mygeoindex",
                SearchParams = searchParams
            };
            var results = _bucket.Query(searchQuery);

// ... snip ...

All I need to return from this endpoint is a list of the results: each hotel’s coordinates and the hotel’s name & location. I created a GeoSearchResult class for this.

public class GeoSearchResult
{
    public double Latitude { get; set; }
    public double Longitude { get; set; }
    public InfoWindow InfoWindow { get; set; }
}

public class InfoWindow
{
    public string Content { get; set; }
}

I’ve constructed this class to match the Google Maps plugin that I’ll be using later.

Finally, I’ll use this class to return some results from the endpoint.

// ... snip ...

            var list = new List<GeoSearchResult>();
            foreach (var hit in results.Hits)
            {
                // *** this part shouldn't be necessary
                // the geo and name should come with the search results
                // but there's an SDK bug NCBC-1651
                var doc = _bucket.Get<dynamic>(hit.Id).Value;
                // ****************
                list.Add(new GeoSearchResult
                {
                    Latitude = doc.geo.lat,
                    Longitude = doc.geo.lon,
                    InfoWindow = new InfoWindow
                    {
                        Content = doc.name + "<br />" +
                            doc.city + ", " +
                            doc.state + " " +
                            doc.country
                    }
                });
            }
            return Ok(list);
        }

A "distance" search is another way to perform geospatial queries. This time, instead of a box, it will be more like a circle. You supply a single coordinate, and a distance. The distance will be the radius from that point.

public class PointSearch
{
    public double Latitude { get; set; }
    public double Longitude { get; set; }
    public int Distance { get; set; }
    // miles is being assumed as the unit
    public string DistanceWithUnits => Distance + "mi";
}

I’m defaulting it to miles, but certainly you can use kilometers instead, or present the option in the UI.

The endpoint will be very similar to the bounding box endpoint, except that it uses GeoDistanceQuery.

[Route("api/Point")]
[HttpPost]
public IActionResult Point([FromBody] PointSearch point)
{
    var query = new GeoDistanceQuery();
    query.Latitude(point.Latitude);
    query.Longitude(point.Longitude);
    query.Distance(point.DistanceWithUnits);
    var searchParams = new SearchParams()
        // .Fields("geo", "name") // omitting because of bug NCBC-1651
        .Limit(10)
        .Timeout(TimeSpan.FromMilliseconds(10000));
    var searchQuery = new SearchQuery
    {
        Query = query,
        Index = "mygeoindex",
        SearchParams = searchParams
    };
    var results = _bucket.Query(searchQuery);

    var list = new List<GeoSearchResult>();
    foreach (var hit in results.Hits)
    {
        // *** this part shouldn't be necessary
        // the geo and name should come with the search results
        // but there's an SDK bug NCBC-1651
        var doc = _bucket.Get<dynamic>(hit.Id).Value;
        // ****************
        list.Add(new GeoSearchResult
        {
            Latitude = doc.geo.lat,
            Longitude = doc.geo.lon,
            InfoWindow = new InfoWindow
            {
                Content = doc.name + "<br />" +
                          doc.city + ", " +
                          doc.state + " " +
                          doc.country
            }
        });
    }
    return Ok(list);
}

At this point, you can start testing these endpoint with Postman or Fiddler if you’d like. But it will be so much nice to see this on a map.

Auerlia and Google Maps

In Aurelia, I’ve created two components: geosearchbox and geosearchpoint.

Auerlia components

Each of them will have a Google Maps component that the user can interact with. These maps will be centered on San Francisco, because that’s where a lot of the hotels in "travel-sample" are located.

Bounding Box search component

The google-map` component has a map-click.delegate that will will fire whenever the users clicks on the map. In geosearchbox.html:

<google-map
    if.bind="markers"
    map-click.delegate="clickMap($event)"
    latitude="37.780986253433895"
    longitude="-122.45291600632277"
    zoom="12"
    markers.bind="markers">
</google-map>

markers is simply an array containing coordinates of search results that should appear on the map. Initially it will be empty.

When the user first clicks the map, this will set the first coordinate (top left) in the form. In geosearchbox.ts:

public clickMap(event : any) {
    var latLng = event.detail.latLng,
        lat = latLng.lat(),
        lng = latLng.lng();

    // only update top left if it hasn't been set yet
    // or if bottom right is already set
    if (!this.longitudeTopLeft || this.longitudeBottomRight) {
        this.longitudeTopLeft = lng;
        this.latitudeTopLeft = lat;
        this.longitudeBottomRight = null;
        this.latitudeBottomRight = null;
    } else {
        this.longitudeBottomRight = lng;
        this.latitudeBottomRight = lat;
    }
}

Then, click another spot on the map. This will set the second coordinate (bottom right).

My implementation is very bare bones. No fancy graphics and no validation of the second coordinate being to the bottom right of the first. The fields on a form will simply be populated with the latitude and longitude. In geosearchbox.html:

<p>
    Bounding box search:
    <br />
    Latitude (top left):
        <input type="text" value="${ latitudeTopLeft }" />
    Longitude (top left):
        <input type="text" value="${ longitudeTopLeft }" />
    <br />
    Latitude (bottom right):
        <input type="text" value="${ latitudeBottomRight }" />
    Longitude (bottom right):
        <input type="text" value="${ longitudeBottomRight }" />
    <br />
    <input
        if.bind="latitudeTopLeft && latitudeBottomRight"
        click.trigger="searchClick()"
        type="button"
        name="search"
        value="Search" />
</p>

Once you’ve selected two coordinates, a search button will appear. Click that to post these coordinates to the endpoint created earlier, and it will trigger the searchClick() method as seen in geosearchbox.ts:

public searchClick() {
    let boxSearch = {
        latitudeTopLeft: this.latitudeTopLeft,
        longitudeTopLeft: this.longitudeTopLeft,
        latitudeBottomRight: this.latitudeBottomRight,
        longitudeBottomRight: this.longitudeBottomRight
    };

    console.log("POSTing to api/Box: " + JSON.stringify(boxSearch));

    this.http.fetch('api/Box', { method: "POST", body: json(boxSearch) })
        .then(result => result.json() as Promise<any[]>)
        .then(data => {
            this.markers = data;
        });
}

When Aurelia, Google Maps, ASP.NET Core, and Couchbase all work together, it looks like this:

Geospatial bounding box

Distance Search

Implementing the "distance" geostatial query will be similar to the bounding box UI. This time, you only need to click a single point on the map. But, you will need to type in a distance (in miles).

The google-map component will look identical. The clickMap function is different:

public clickMap(event: any) {
    var latLng = event.detail.latLng,
        lat = latLng.lat(),
        lng = latLng.lng();

    this.longitude = lng;
    this.latitude = lat;
}

Specify a distance (in miles), and then click 'search' to make a POST request to the endpoint we wrote earlier.

geosearchbox.html:

    <p>
        Distance search:
        <br />
        Latitude: <input type="text" value="${ latitude }" />
        Longitude: <input type="text" value="${ longitude }" />
        <br />
        Distance (miles): <input type="text" value="${ distance }" />
        <br />
        <input if.bind="latitude" click.trigger="searchClick()" type="button" name="search" value="Search" />
    </p>

geosearchbox.ts:

    public searchClick() {
        let pointSearch = {
            latitude: this.latitude,
            longitude: this.longitude,
            distance: this.distance
        };

        console.log("POSTing to api/Point: " + JSON.stringify(pointSearch));

        this.http.fetch('api/Point', { method: "POST", body: json(pointSearch) })
            .then(result => result.json() as Promise<any[]>)
            .then(data => {
                this.markers = data;
            });
    }
}

Below is a clip of the search in motion. Note how the results change as I move the coordinate around.

Geospatial distance point search query

Summary

With Couchbase’s built-in geospatial indexing and search feature, all the math and the searching is delegated to the Couchbase Data Platform. So you can focus on building a killer UI (better than mine anyway) and rock-solid business logic.

Be sure to check out the documentation for a complete overview of the geospatial capabilities of Couchbase.

If you need help or have questions, please check out the Couchbase Server forums, and if you have any questions about the Couchbase .NET SDK, check out the .NET SDK forums.

If you’d like to get in touch with me, please leave a comment or find me on Twitter @mgroves.

Swashbuckle is a handy library to easily bring Swagger support to your ASP.NET Core (or ASP.NET) application. It is especially handy when developing an HTTP based API. It creates a form of interactive documentation based on the OpenAPI Specification.

Before diving into Swashbuckle: Merry Christmas! This blog is being posted on December 25th, 2017. It’s the final post of the very first C# Advent Calendar. Please check out the other 24 posts in the series! This event has gone so well, that I’m already planning on doing it again in 2018. Thank you, again, to everyone who participated (whether you are a writer or you’ve just been following along).

The full source code used in this example is available on Github.

ASP.NET Core HTTP API

I’m going to assume some level of familiarity with ASP.NET Core and creating a REST API. Here’s an example of a GET and a POST. These endpoints are reading/writing from a JSON text file (in a way that is probably not thread-safe and definitely not efficient, but it’s fine for this example).

public class ValuesController : Controller
{
    [HttpGet]
    [Route("api/teams")]
    public IActionResult GetTeams()
    {
        var jsonFile = System.IO.File.ReadAllText("jsonFile.json");
        var teams = JsonConvert.DeserializeObject<List<Team>>(jsonFile);
        return Ok(teams);
    }

    [HttpPost]
    [Route("api/team")]
    public IActionResult PostTeam([FromBody]Team team)
    {
        var jsonFile = System.IO.File.ReadAllText("jsonFile.json");
        var teams = JsonConvert.DeserializeObject<List<Team>>(jsonFile);
        teams.Add(team);
        System.IO.File.WriteAllText("jsonFile.json",JsonConvert.SerializeObject(teams));
        return Ok(team);
    }

    // etc...

To try out the GET endpoint, the simplest thing I can do is open a browser and view the results. But to try out the POST endpoint, I need something else. I could install Postman or Fiddler (and you should). Here’s how that would look.

Postman

Postman is great for interacting with endpoints, but Postman alone doesn’t really tell us anything about the endpoint or the system as a whole. This is where Swagger comes in.

Swagger

Swagger is a standard way to provide specifications for endpoints. Usually, that specification is automatically generated and then used to generate an interactive UI.

We could write the Swagger spec out by hand, but fortunately ASP.NET Core provides enough information to generate a spec for us. Look at the PostTeam action above. Just from reading that we know:

  • It expects a POST

  • The URL for it is /api/team

  • There’s a Team class that we can look at to see what kind of body is expected

From that, we could construct a Swagger spec like the following (I used JSON, you can also use YAML).

{
	"swagger": "2.0",
	"info": { "version": "v1", "title": "Sports API" },
	"basePath": "/",
	"paths": {
		"/api/team": {
			"post": {
				"consumes": ["application/json"],
				"parameters": [{
					"name": "team",
					"in": "body",
					"required": false,
					"schema": { "$ref": "#/definitions/Team" }
				}]
			}
		}
	},
	"definitions": {
		"Team": {
			"type": "object",
			"properties": {
				"name": { "type": "string" },
				"stadiumName": { "type": "string" },
				"sport": { "type": "string" }
			}
		}
	}
}

But why on earth would you want to type that out? Let’s bring in a .NET library to do the job. Install Swashbuckle.AspNetCore with NuGet (there’s a different package if you want to do this with ASP.NET).

You’ll need to add a few things to Startup.cs:

In the ConfigureServices method:

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new Info { Title = "Sports API", Version = "v1"});
});

In the Configure method:

app.UseSwagger();

Aside: With ASP.NET, NuGet actually does all this setup work for you.

Once you’ve done this, you can open a URL like http://localhost:9119/swagger/v1/swagger.json and see the generated JSON spec.

Swagger spec in JSON

Swagger UI with Swashbuckle

That spec is nice, but it would be even nicer if we could use the spec to generate a UI.

Back in the Configure method, add this:

app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "Sports API v1");
});

Now, open your site and go to /swagger:

Swagger UI generated by Swashbuckle

Some cool things to notice:

  • Expand/collapse by clicking the URL of an endpoint (note that you must use Route attributes for Swashbuckle to work with ASP.NET Core).

  • "Try it out!" buttons. You can execute GET/POST right from the browser

  • The "parameter" of the POST method. Not only can you paste in some content, but you get an example value that acts like a template (just click it).

Giving some swagger to your Swagger

Swagger and Swashbuckle have done a lot with just a little bit. It can do even more if we add a little more information in the code.

  • Response: The ProducesResponseType attribute will let Swagger know what the response will look like (this is especially useful if you are using IActionResult and/or an endpoint could return different types in different situations).

  • Comments: If you are using XML comments, you can have these included with the Swagger output.

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new Info { Title = "Sports API", Version = "v1" });
    var filePath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "swashbuckle-example.xml");
    c.IncludeXmlComments(filePath);
});

(Also make sure you XML Documentation output for your project enabled)

Here’s an example of a GetTeams method with both XML comments and ProducesResponseType:

/// <summary>
/// Gets all the teams stored in the file
/// </summary>
/// <remarks>Baseball is the best sport</remarks>
/// <response code="200">List returned succesfully</response>
/// <response code="500">Something went wrong</response>
[HttpGet]
[Route("api/teams2")]
[ProducesResponseType(typeof(Team), 200)]
public IActionResult GetTeams2()
{
    var jsonFile = System.IO.File.ReadAllText("jsonFile.json");
    var teams = JsonConvert.DeserializeObject<List<Team>>(jsonFile);
    return Ok(teams);
}
  • Customize your info: there’s more to the Info class than just Title and Version. You can specify a license, contact, etc.

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new Info
    {
        Title = "Sports API",
        Version = "v1",
        Description = "An API to list and add sports teams",
        TermsOfService = "This is just an example, not for production!",
        Contact = new Contact
        {
            Name = "Matthew Groves",
            Url = "https://crosscuttingconcerns.com"
        },
        License = new License
        {
            Name = "Apache 2.0",
            Url = "http://www.apache.org/licenses/LICENSE-2.0.html"
        }
    });
    var filePath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "swashbuckle-example.xml");
    c.IncludeXmlComments(filePath);
});

Here’s a screenshot of the UI that has all three of the above enhancements: response type, XML comments, and more customized info.

Swagger with more swagger

Summary

Working on HTTP-based APIs? Bring Swashbuckle and Swagger into your life!

More resources:

Thanks again for reading the 2017 C# Advent!

This is a repost that originally appeared on the Couchbase Blog: ASP.NET Core with Couchbase: Getting Started.

ASP.NET Core is the newest development platform for Microsoft developers. If you are looking for information about plain old ASP.NET, check out ASP.NET with Couchbase: Getting Started.

ASP.NET Core Tools to Get Started

The following video will take you from having no code to having an HTTP REST API that uses Couchbase Server, built with ASP.NET Core.

These tools are used in the video:

Getting Started Video

In the video, I touch quickly on Scan Consistency. For more details on that, check out the Scan Consistency documentation or read a blog post that I wrote introducing AtPlus, which also covers the other types of Scan Consistency.

Summary

This video gives you the absolute minimum to get started with Couchbase by walking you through a simple CRUD application.

If you have any questions, please leave a comment. Or, you can always ask me questions on Twitter @mgroves.

This is a repost that originally appeared on the Couchbase Blog: ASP.NET with Couchbase: Getting Started.

ASP.NET is the development platform that most Microsoft developers use. At the Couchbase Connect Silicon Valley 2017 conference, I spoke to some .NET developers in a workshop. I asked them what type of content they’d like to see me create that would be most useful for them. The answer was: videos on getting started.

ASP.NET Tools to Get Started

The below video takes you from having no code to having an HTTP-based REST API that uses Couchbase Server, built with ASP.NET.

The video uses the following tools:

Getting Started Video

In the video, I briefly gloss over Scan Consistency. For more details on that, check out the Scan Consistency documentation or read a blog post that I wrote introducing AtPlus, which also covers the other types of Scan Consistency.

Summary

This video gives you the absolute minimum to get started with Couchbase by walking you through a simple CRUD application. Stay tuned for a similar video on getting started with ASP.NET Core.

If you have any questions, please leave a comment. Or, you can always ask me questions on Twitter @mgroves.

This is a repost that originally appeared on the Couchbase Blog: Distributed session with ASP.NET Core and Couchbase.

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 web site, especially if you don’t want to use sticky sessions.

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 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:

  • Use the NuGet UI (see below), or

  • Install-Package Couchbase.Extensions.Session -Version 1.0.0-beta2 with the Package manager, or

  • 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, setup 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 to 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.

And please reach out to me with questions on all things .NET and Couchbase by leaving a comment below or finding me on Twitter @mgroves.

Matthew D. Groves

About the Author

Matthew D. Groves lives in Central Ohio. He works remotely, loves to code, and is a Microsoft MVP.

Latest Comments

Twitter