The main feature of a middleware is to handle requests and response that is passed through its pipeline. In this article, we can see how to create a custom middleware for Asp.Net Core
public class ResponseMsg
{
private readonly RequestDelegate next;
public ResponseMsg(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context)
{
await context.Response.WriteAsync("Before next Pipeline");
await next.Invoke(context);
await context.Response.WriteAsync("After the pipeline");
}
}
Invoke Method
The invoke method will take the HttpContext as parameter, the method can call the next application pipeline. The invoke method can have additional parameter and it can be populated through the dependency injection.
To add the middleware to application pipeline
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseMiddleware<ResponseMsg>();
app.Run(async context => await context.Response.WriteAsync("In startup"));
}
}
Middleware using Dependency injection
public interface IApplicationMsg
{
void AddMessage(HttpContext context);
}
public class ApplicationMsg : IApplicationMsg
{
public void AddMessage(HttpContext context)
{
context.Response.WriteAsync("Application Msg!!");
}
}
Add the Service using the dependency injection.
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IApplicationMsg, ApplicationMsg>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseMiddleware<ApplicationMsgMiddleware>();
app.Run(async context => await context.Response.WriteAsync("In startup"));
}
}
AddSingleton – It is a Singleton service which creates a single instance throughout the application.
AddTransient- It is stateless service services are created each time they are requested
AddScoped – It is created for one per request.
How to add the custom middleware component with pipeline
public static class CustomMiddleWareBuilder
{
public static void UseMessage(this IApplicationBuilder builder)
{
builder.UseMiddleware<ApplicationMsgMiddleware>();
}
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseMessage();
}
Leave a comment