We'll create a new project and write our first middleware. We can observe the execution mechanism of middleware with this project.
- First, let's create a middleware class:
public class MyMiddleware1 { private readonly RequestDelegate _next; public MyMiddleware1(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext httpContext) { await httpContext.Response.WriteAsync ("Hello from first middleware before Request n"); await _next(httpContext); await httpContext.Response.WriteAsync ("Hello from first middleware after Request n"); } }
A middleware class does not inherit from any class or interface, but has to respect some rules:
-
- Having a public constructor that takes a RequestDelegate type as parameter. ...