Free Web Development Online Tutorials, Learn to Code
Asp.net Core Middleware Example, httpclient middleware, default middleware, custom default middleware example

Asp.net Core Middleware Example

In this tutorial, you will learn how to use middleware in Asp.net Core step by step, how to implement httpclient middleware, default middleware, custom default middleware etc.

What is Middleware in .Net Core?

"Middleware is software that's assembled into an app pipeline to handle requests and responses." -MSDN

Middleware is an external components that form a pipeline between a server and application, to inspect, route, modify request and response messages for that specific purpose.

Middleware has a number of application components that are incorporated into the ASP.NET HTTP pipeline.

We can develop a code with a purpose to manipulate the requests and responses.

Or you can say Middleware is a mechanism that allows to manipulate Http-Pipeline, which was not possible in earlier Asp.net Framework (HttpHandlers, HttpModules)

You may be read more about Asp.net Core Middleware.

Here we more focus on how to configure middleware using Run, Map, and Use extension methods.

Add Middleware in Pipeline

You can add Middleware in Pipeline using IApplicationBuilder, here we see how we can add a new service to Middleware, Some commonly used middleware are UseMvc(), UseAuthentication(), UseDeveloperExceptionPage()

Here are some example of default middleware, We simply can configure default middleware just by adding built in default extension methods in Configure method of startup file.

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
 {     
    app.UseMvc();
    app.UseAuthentication();
    app.UseDeveloperExceptionPage();
    app.UseStaticFiles(); 
}		

Middlewares are executed in the order they are configured. You can change the order; the first configured middleware will get executed first.

Custom Middleware in Asp.net Core

You can build your custom middleware and add to request pipeline in Startup Configure method

Here are the namespace you required to create a custom Middleware, here in example we have created "WTRCustomMiddleware"

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
Create the Middleware class
    public class WTRCustomMiddleware
    {
        private readonly RequestDelegate _next;
    public WTRCustomMiddleware(RequestDelegate next)
    {
        _next = next;
    }
    public async Task InvokeAsync(HttpContext context)
    {
        await context.Response.WriteAsync("- Before Message -  \n\r");
        await _next(context);
        await context.Response.WriteAsync("\n\r - After Message - ");
    }
    }

Now add a static extensions class for extension method

    public static class WTRCustomMiddlewareExtensions
    {
        public static IApplicationBuilder UseWTRCustomMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<WTRCustomMiddleware>();
        }
    }

Now your custom middleware class is ready simply add to pipeline, open your startup.cs class, place the following code in Configure method.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{ app.UseWTRCustomMiddleware();
app.Run(async (context) =>
    {
        await context.Response.WriteAsync("Welcome to WebTrainingRoom!");
    });
} 

Map Middleware for different path

We can implement different Middleware for different path, here is an example of two Middleware pipeline, we want to map them for different path.

private static void ExecuteMiddleware1(IApplicationBuilder app)
{
app.Run(async context =>
{
await context.Response.WriteAsync("Execute Middleware 1");
});
}
private static void ExecuteMiddleware2(IApplicationBuilder app)
{
app.Run(async context =>
    {
        await context.Response.WriteAsync("Execute Middleware 2");
    });
}

Here is how you can Map Middleware in Configure method

public void Configure(IApplicationBuilder app)
{
app.Map("/mapPath1", ExecuteMiddleware1);
app.Map("/mapPath2", ExecuteMiddleware2);
app.Run(async context =>
        {
            await context.Response.WriteAsync("Hello from No Match.");
        });
    }

Here are some more middleware examples you should look at, logging and exception handling are two frequently used functionalities in any application development lifecycle, in below tutorial you can learn how to use middleware for logging and error handling.

 
Asp.net Core Middleware Examples
ASP.NET MVC Interview Questions Answers

online courses
Asp.Net Core C# Examples | Join Asp.Net MVC Course