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.

Middleware in Asp.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)

Add Middleware in Pipeline

You can sdd 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()

These are example of default middleware.

 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

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.");
        });
    }

You should also look at the examples below

Comment
Name
Email
Website
Subscribe
 

hire remote asp.net developer
Middleware in Asp.net Core

ASP.NET MVC Interview Questions Answers

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