Middleware Extensions

Middleware extensions are the pipeline used for requests in asp.net core. Each middleware plugin can process part or all of the request, and then either choose to return the result or pass on down to the next piece of middleware

pipeline

Benefits of using Middleware Plugins

There are many uses for middleware within ASP.Net Core, a few examples are:

  • Add security headers
  • User session management
  • Extracting Marketing data

The list is as open as the developers mind.

UserSession Manager Example

Included in the sample source code is a UserSession Manager. This plugin is a Middleware extension that looks for an existing session, creates one if one does not already exist and then add's it to the HttpContext for use in Controllers loaded into the application.

The UserSession is highly optimised and allows the developer to store custom information to identify each vistor to a website. If required GeoIp data can be attached to the UserSession class.

A variety of reporting options are available to make maximum use of the Seo data collected.

To access the user session within a controller, simply obtain a reference from the HttpContext instance.


using System;

using Microsoft.AspNetCore.Mvc;

using Shared.Classes;

namespace DemoWebsitePlugin.Controllers
{
public class ServicesController : Controller
{
public IActionResult Index()
{
UserSession session = (UserSession)HttpContext.Items["UserSession"];

if (String.IsNullOrEmpty(session.UserName))
{
// user is not logged in, do something...
}

return View();
}

public IActionResult Middleware()
{
return View();
}
}
}