Custom Conventional Middleware in Asp.net Core

Custom Conventional Middleware in Asp.net Core
ASP.NET Core middleware comes in two flavors: conventional and factory-based. Conventional middleware, as shown in your example, is a simple yet powerful way to encapsulate custom logic for processing HTTP requests and responses.
Key Characteristics
Class-Based: Conventional middleware is implemented as a class.
Constructor Injection: It receives dependencies (if any) through its constructor.
Invoke Method: This is the heart of the middleware, containing the logic that handles each request.
RequestDelegate: The Invoke method takes a RequestDelegate parameter (_next in your example). This delegate represents the next middleware in the pipeline.
Flexibility: You have full control over the request and response objects within the Invoke method.
Code Breakdown: HelloCustomMiddleware
 
// HelloCustomMiddleware.cs
public class HelloCustomMiddleware
{
    private readonly RequestDelegate _next;
 
    public HelloCustomMiddleware(RequestDelegate next)
    {
        _next = next;
    }
 
    public async Task Invoke(HttpContext httpContext)
    {
        if (httpContext.Request.Query.ContainsKey(“firstname”) &&
            httpContext.Request.Query.ContainsKey(“lastname”))
        {
            string fullName = httpContext.Request.Query[“firstname”] + ” ” + httpContext.Request.Query[“lastname”];
            await httpContext.Response.WriteAsync(fullName);
        }
        await _next(httpContext);
    }
}
 
// Extension method for easy registration
public static class HelloCustomModdleExtensions
{
    public static IApplicationBuilder UseHelloCustomMiddleware(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<HelloCustomMiddleware>();
    }
}
 
Let’s analyze each part:
Constructor: The constructor receives the RequestDelegate, which is stored for later use to invoke the next middleware in the pipeline.
Invoke Method:
It checks if the query string contains both “firstname” and “lastname” parameters.
If so, it combines the values into a fullName string and writes it to the response.
Crucially: It calls await _next(httpContext); to continue the middleware chain. This line ensures that the request is passed on to subsequent middleware components, even if a full name is generated.
By design, any code after this line, such as the comment “//after logic”, would not execute for requests containing both “firstname” and “lastname”, as the await _next(httpContext); line immediately transfers control to the next middleware in the pipeline.
UseHelloCustomMiddleware Extension: This extension method simplifies the registration process by hiding the details of instantiating and using your custom middleware class.
 
 
Program.cs (or Startup.cs): Using the Middleware
// … other middleware …
app.UseMyCustomMiddleware();
app.UseHelloCustomMiddleware();
// …

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply