Monday, May 9, 2016

ASP.NET 5 (ASP.NET Core 1.0) Middleware : Use, Map, MapWhen and Run

Middleware plays a major role in ASP.NET 5 (ASP.NET Core 1.0) application pipeline. Even the roles of both modules and handlers have been taken over by Middleware and it is important to learn the various ways of configuring Middleware in a ASP.NET 5 (ASP.NET Core 1.0) application.

On ASP.NET 5 (ASP.NET Core 1.0), when configuring Middleware in the application pipeline on IApplicationBuilder (uses to build the application request pipeline),  we have fours options.
  • Use
  • Map
  • MapWhen
  • Run
In this post, let’s see in detail the differences between each of these Middleware configuration options and their usage.

Use


Basically Use adds a Middleware to the application pipeline and it has the capability either to pass the request to next delegate or to short circuit the request pipeline.
app.Use(async (context, next) =>
{
    await context.Response.WriteAsync("Hello World! \n");
    await next.Invoke();
});
So here by calling next.Invoke(), we will be passing the request to the next delegate (basically this is the next Middleware which is defined in the code, the Middleware will get added to the application pipeline in the order they are defined in the code). If we remove calling next.Invoke() we are short circuiting the application pipeline.

Map


We can use Map method to specify if the request path starts with a specific path, add a specific Middleware.
app.Map("/contactus", HandleContactUs);
private static void HandleContactUs(IApplicationBuilder app)
{
   app.Run(async context =>
   {
       await context.Response.WriteAsync("Contact Us");
   });
}
So here if we navigate to “http://localhost:xxxx/contactus”, the request will get branched to HandleContactUs delegate and what ever the other Middlewares defined below app.Map() won’t get added to the pipleline.

MapWhen


Here the concept is same as Map except we have more control over the condition (based on the URL, request headers, query strings, etc) which we checks to add the Middleware to the pipeline.
app.MapWhen(context =>
{
    return context.Request.Query.ContainsKey("pid");
}, HandleProductDetail);

Here if the request URL contains a “pid”, then the request will be branched off to HandleProductDetail delegate.
private static void HandleProductDetail(IApplicationBuilder app)
{
    app.Run(async context =>
    {
        await context.Response.WriteAsync("Product Details");
    });
}

Run


Run will add a Middleware and it will be the end of the request pipeline. It will not call the next delegate.
app.Run(async context =>
{
    await context.Response.WriteAsync("Main Content");
});
I am uploading the sample code to OneDrive.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment