Posted by Anuraj on Wednesday, July 8, 2015 Reading time :1 minute
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
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.
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.
And you can create an extension method, which will help you to inject the middleware to the ASP.NET pipeline like this.
In Startup.cs, Configure method, you can use this middleware like this.
Happy Programming :)
What do you think? I would like to hear your thoughts, suggestions, and questions in the comments section below.