Build your first ASP.NET 5 middleware

Posted by Anuraj on Wednesday, July 8, 2015

.Net .Net 3.0 / 3.5 ASP.Net ASP.Net MVC

This post is about developing your own ASP.NET 5 middleware. What is Middleware - The definition of “Middleware” varies depends on its context, but in ASP.NET 5, the definition provided by the OWIN specification is probably closest - Pass through components that form a pipeline between a server and application to inspect, route, or modify request and response messages for a specific purpose. Middleware components are similar to ASP.NET HttpModules and/or HttpHandlers. You can access the ASP.NET request pipeline via Startup.cs class, Configure() method. Configure method helps developers to plugin middleware components. Here is the Startup.cs from HelloMVC sample project

using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;

namespace HelloMvc
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app)
        {
            app.UseErrorPage();
            app.UseMvcWithDefaultRoute();
            app.UseWelcomePage();
        }
    }
}

MVC Middleware injected to the request pipeline using app.UseMvcWithDefaultRoute(), which is an extension method to IApplicationBuilder type. For building middleware you don’t need to implement any interface or abstract classes; middleware components are identified by convention (Duck typing).You require a public constructor, which accepts a RequestDelegate class. A RequestDelegate is a function that takes an HttpContext instance and returns a Task.

public delegate Task RequestDelegate(HttpContext context);

The HttpContext is similar to the old versions of ASP.NET, but it trimmed down version. And you require a Invoke method, with HttpContext parameter, your middleware code should be inside this. ASP.NET runtime will be calling the invoke method, and it is where you pass control on to the next component in the pipeline if required. Control is passed to the next component by calling await _next(context).

Here is the HelloWorld middleware, which prints a HelloWorld in the browser.

public class HelloWorldMiddleware
{
    RequestDelegate _next;
    public HelloWorldMiddleware(RequestDelegate next)
    {
        _next = next;
    }
    public async Task Invoke(HttpContext context)
    {
        context.Response.ContentType = "text/html";
        context.Response.StatusCode = 200;
        await context.Response.WriteAsync("HelloWorld!");
        await _next(context);
    }
}

And you can create an extension method, which will help you to inject the middleware to the ASP.NET pipeline like this.

public static class BuilderExtensions
{
    public static IApplicationBuilder UseHelloWorld(this IApplicationBuilder app)
    {
        return app.UseMiddleware<HelloWorldMiddleware>();
    }
}

In Startup.cs, Configure method, you can use this middleware like this.

public void Configure(IApplicationBuilder app)
{
    app.UseErrorPage();
    app.UseStaticFiles();
    app.UseHelloWorld();
    app.UseMvc(routes =>
    {
        routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
    });
}

Happy Programming :)



Did you like this article? Share it with your friends

Facebook Twitter Google+ LinkedIn Reddit StumbleUpon



MVP
Subscribe
Archives


Copyright © 2017 - Anuraj P. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Hosted with ❤ by GitHub