3 Ways to Define Middleware in ASP NET Core

Listen to this Post

Middleware in ASP .NET Core allows you to introduce additional logic before or after executing an HTTP request. It is an excellent choice for solving cross-cutting concerns in your application. Here are three approaches to define custom middleware:

1. Request Delegates

2. Convention-based

3. Factory-based

For a detailed guide, visit: https://lnkd.in/ezupCfNb

You Should Know:

1. Request Delegates

Request delegates are the simplest way to define middleware. They are inline methods that handle HTTP requests and responses.

public void Configure(IApplicationBuilder app)
{
app.Run(async context =>
{
await context.Response.WriteAsync("Hello from Request Delegate Middleware!");
});
}

2. Convention-based Middleware

Convention-based middleware follows a specific pattern. It requires a class with an `Invoke` or `InvokeAsync` method.

public class ConventionMiddleware
{
private readonly RequestDelegate _next;

public ConventionMiddleware(RequestDelegate next)
{
_next = next;
}

public async Task InvokeAsync(HttpContext context)
{
await context.Response.WriteAsync("Hello from Convention-based Middleware!");
await _next(context);
}
}

public static class MiddlewareExtensions
{
public static IApplicationBuilder UseConventionMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<ConventionMiddleware>();
}
}

3. Factory-based Middleware

Factory-based middleware is created using a factory pattern. It is useful for more complex scenarios.

public class FactoryMiddleware : IMiddleware
{
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
await context.Response.WriteAsync("Hello from Factory-based Middleware!");
await next(context);
}
}

public static class MiddlewareExtensions
{
public static IApplicationBuilder UseFactoryMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<FactoryMiddleware>();
}
}

What Undercode Say:

Middleware is a powerful feature in ASP .NET Core that helps manage cross-cutting concerns like logging, authentication, and error handling. Whether you use request delegates, convention-based, or factory-based middleware, each approach has its own advantages. For more advanced scenarios, factory-based middleware provides flexibility, while convention-based middleware is great for simplicity. Always choose the approach that best fits your application’s architecture.

Related Commands and Tools:

  • Use `dotnet new webapi` to create a new ASP .NET Core project.
  • Use `dotnet run` to start your application.
  • Use `app.UseMiddleware()` to register custom middleware.
  • Explore more at ASP .NET Core Documentation.

References:

Reported By: Milan Jovanovic – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅

Join Our Cyber World:

💬 Whatsapp | 💬 TelegramFeatured Image