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; }
// 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(); // …