How to do it...

We'll create a new project and write our first middleware. We can observe the execution mechanism of middleware with this project.

  1. 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. ...

Get ASP.NET Core MVC 2.0 Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.