# Middleware Pipeline

Course: [Blazor](https://www.devtutorials.ai/learn/blazor) · Section: Application Security
Source: https://www.devtutorials.ai/learn/blazor/application-security/middleware-pipeline

> How every request passes through middleware: the ASP.NET Core request pipeline, Program.cs setup, execution order, built-in middleware (static files, HTTPS redirection, exception handling, status code pages), Use, Run and Map, short-circuiting, and inline and class middleware.

## Middleware Introduction

- You know from **API Integration** that the browser sends a **request** and the server sends back a **response**.
- Before your page sees a request, small pieces of code on the server look at it first. Each piece is called **middleware**.
- A middleware can **check** the request, **change** it, **answer** it by itself, or **pass it on** to the next middleware.
- On the way back, the same middleware can look at the response too.

**Real-World Example:**

Think of the Tea Shop's web server as a building with a few gates. A visitor (the request) walks through them in order:

1. **HTTPS gate**: "Use the secure door, please."
2. **Error gate**: "If anything goes wrong inside, I will show a polite error page."
3. **Files gate**: "Asking for `app.css`? Here it is." The visitor goes no further.
4. **Your page**: everyone else reaches the Blazor page that makes the answer.

<figure className="blz-fig">
<svg viewBox="0 0 640 185" role="img" aria-labelledby="fig-mw-intro">
  <title id="fig-mw-intro">Animation: a request leaves the browser and passes three middleware boxes, HTTPS, Errors and Static files, to reach the endpoint, your page. The response then travels back through the same three boxes to the browser.</title>
  <defs><marker id="fig-mw-intro-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="blu" x="10" y="50" width="90" height="90" rx="12" />
  <text className="t m" x="55" y="100" textAnchor="middle" style={{ fontSize: 12, fontWeight: 700 }}>Browser</text>
  <rect className="pur" x="130" y="40" width="100" height="110" rx="12" />
  <text className="t m" x="180" y="100" textAnchor="middle" style={{ fontSize: 12 }}>HTTPS</text>
  <rect className="pur" x="250" y="40" width="100" height="110" rx="12" />
  <text className="t m" x="300" y="100" textAnchor="middle" style={{ fontSize: 12 }}>Errors</text>
  <rect className="pur" x="370" y="40" width="100" height="110" rx="12" />
  <text className="t m" x="420" y="100" textAnchor="middle" style={{ fontSize: 12 }}>Static files</text>
  <rect className="grn" x="500" y="50" width="130" height="90" rx="12" />
  <text className="t m" x="565" y="94" textAnchor="middle" style={{ fontSize: 12, fontWeight: 700 }}>Endpoint</text>
  <text className="t" x="565" y="112" textAnchor="middle" style={{ fontSize: 11 }}>your page</text>
  <path className="line" d="M100 62 H496" markerEnd="url(#fig-mw-intro-a)" />
  <path className="line" d="M500 128 H104" markerEnd="url(#fig-mw-intro-a)" />
  <text className="t m" x="300" y="28" textAnchor="middle" style={{ fontSize: 11 }}>request goes in</text>
  <text className="t m" x="300" y="172" textAnchor="middle" style={{ fontSize: 11 }}>response comes back</text>
  <circle r="7" style={{ fill: "#7c3aed" }}>
    <animate attributeName="cx" values="100;565;565;100;100" keyTimes="0;0.45;0.55;0.95;1" dur="6s" repeatCount="indefinite" />
    <animate attributeName="cy" values="62;62;128;128;128" keyTimes="0;0.45;0.55;0.95;1" dur="6s" repeatCount="indefinite" />
  </circle>
</svg>
<figcaption>Every request passes the middleware in order. The response comes back the same way.</figcaption>
</figure>

## ASP.NET Core Request Pipeline

- Blazor apps run on **ASP.NET Core**, the .NET framework for web servers.
- The middleware, joined one after another, form the **request pipeline**, like water flowing through a pipe.
- At the end of the pipe is the **endpoint**: the code that makes the real answer, such as a Blazor page or an API action.
- Each middleware gets a **`next`**: a way to call the middleware after it. Calling `next` passes the request on.
- Every request gets a **`HttpContext`**: one object with the **request** (path, method) and the **response** (status code, body). All middleware share it.

In Blazor, the pipeline runs for each **HTTP request**: loading a page, a CSS file or an API call. With interactive rendering, button clicks travel over the open connection (SignalR) or run in the browser, so they **do not** pass through the middleware again.

The code boxes cannot run a real web server. So `FakePipeline.cs` gives them a small pretend pipeline with the **same method names** as the real one: `Use`, `Run`, `Map`, `UseMiddleware`. Its context is called `FakeContext` instead of `HttpContext`.

## Configuring Middleware in Program.cs

- You set up the pipeline in **`Program.cs`**, the file that starts your app.
- It has two halves. **Before** `builder.Build()`, you register services (see **Dependency Injection**). **After** it, you add middleware with `app.Use...()` and endpoints with `app.Map...()`.
- Each `app.Use...` line adds **one** middleware. The order of the lines is the order of the pipeline.

This is the `Program.cs` of a new Blazor Web App:

| Line | What it does |
|---|---|
| `UseExceptionHandler` | Catches errors and shows the `/Error` page |
| `UseHsts` | Tells browsers to always use HTTPS for this site |
| `UseStatusCodePagesWithReExecute` | Shows the `/not-found` page for "not found" answers |
| `UseHttpsRedirection` | Sends `http://` visitors to `https://` |
| `UseAntiforgery` | Protects forms from fake posts from other sites |
| `MapStaticAssets` | Serves files from `wwwroot`, like `app.css` |
| `MapRazorComponents<App>` | Your Blazor pages: the main endpoint |
| `app.Run()` | Starts the server. Always the last line. |

You meet the first four again in **Built-in Middleware** below.

### Your First Pipeline

- **`app.Use(...)`** adds middleware. It gets the `context` and `next`.
- **`app.Run(...)`** adds the **last** step. It gets only the `context`, because nothing comes after it.
- `context.Response.WriteAsync("...")` writes text into the response body.

In the below example, a logging middleware writes a line before and after `next()`, and `app.Run` answers. Click **Send /**.

<p>Status: @status</p>
<p>Body: @body</p>
<ol>
      @foreach (var line in log)
      {
          <li>@line</li>
      }
</ol>

@code {
      private List<string> log = new();
      private int status;
      private string body = "";

      private async Task Send(string path)
      {
          log.Clear();
          var app = new FakePipeline();

          app.Use(async (context, next) =>
          {
              log.Add("Logger: request in for " + context.Request.Path);
              await next();
              log.Add("Logger: response out with " + context.Response.StatusCode);
          });

          app.Run(async context =>
          {
              log.Add("Endpoint: making the answer");
              await context.Response.WriteAsync("Hello from the Tea Shop");
          });

          var result = await app.SendAsync(path);
          status = result.Response.StatusCode;
          body = result.Response.Body;
      }
}
`,
    "Pipeline/FakePipeline.cs": `namespace BlazorApp.Pipeline;

// A small stand-in for the ASP.NET Core pipeline, so the code boxes can run.
// The method names match the real ones you write in Program.cs.
public delegate Task FakeRequestDelegate(FakeContext context);

public class FakeContext
{
      public FakeRequest Request { get; } = new();
      public FakeResponse Response { get; } = new();
}

public class FakeRequest
{
      public string Method { get; set; } = "GET";
      public string Scheme { get; set; } = "https";
      public string Path { get; set; } = "/";
}

public class FakeResponse
{
      public int StatusCode { get; set; } = 200;
      public Dictionary<string, string> Headers { get; } = new();
      public string Body { get; set; } = "";
      public bool HasStarted => Body != "";

      public Task WriteAsync(string text)
      {
          Body += text;
          return Task.CompletedTask;
      }
}

public class FakePipeline
{
      private readonly List<Func<FakeRequestDelegate, FakeRequestDelegate>> steps = new();

      // The files in wwwroot
      public List<string> WwwRoot { get; } = new() { "/app.css", "/favicon.png" };

      // app.Use: run code, then call next() to pass the request on
      public void Use(Func<FakeContext, Func<Task>, Task> middleware) =>
          steps.Add(next => context => middleware(context, () => next(context)));

      // app.Run: the end of the pipeline. There is no next.
      public void Run(FakeRequestDelegate handler) =>
          steps.Add(_ => handler);

      // app.Map: a separate branch for paths that start with pathStart
      public void Map(string pathStart, Action<FakePipeline> configure)
      {
          var branch = new FakePipeline();
          configure(branch);
          steps.Add(next => async context =>
          {
              var path = context.Request.Path;
              if (path == pathStart || path.StartsWith(pathStart + "/"))
              {
                  context.Request.Path = path.Length > pathStart.Length ? path[pathStart.Length..] : "/";
                  await branch.Build()(context);
              }
              else
              {
                  await next(context);
              }
          });
      }

      // app.UseMiddleware<T>: T has a constructor that takes next,
      // and an InvokeAsync(context) method
      public void UseMiddleware<T>() => steps.Add(next =>
      {
          var middleware = Activator.CreateInstance(typeof(T), next)!;
          var invoke = typeof(T).GetMethod("InvokeAsync")!;
          return context => (Task)invoke.Invoke(middleware, new object[] { context })!;
      });

      // Built-in middleware, cut down to their main job
      public void UseHttpsRedirection() => Use(async (context, next) =>
      {
          if (context.Request.Scheme == "http")
          {
              context.Response.StatusCode = 307;
              context.Response.Headers["Location"] = "https://localhost" + context.Request.Path;
              return;
          }
          await next();
      });

      public void UseExceptionHandler(string errorPath) => Use(async (context, next) =>
      {
          try
          {
              await next();
          }
          catch (Exception)
          {
              context.Response.StatusCode = 500;
              context.Response.Body = "";
              context.Request.Path = errorPath;
              await next();
          }
      });

      public void UseStatusCodePagesWithReExecute(string pagePath) => Use(async (context, next) =>
      {
          await next();
          var code = context.Response.StatusCode;
          if (code >= 400 && !context.Response.HasStarted)
          {
              context.Request.Path = pagePath;
              await next();
              context.Response.StatusCode = code;
          }
      });

      public void MapStaticAssets() => Use(async (context, next) =>
      {
          if (WwwRoot.Contains(context.Request.Path))
          {
              await context.Response.WriteAsync("(the file " + context.Request.Path + ")");
              return;
          }
          await next();
      });

      // Sends one pretend request through the pipeline
      public async Task<FakeContext> SendAsync(string path, string scheme = "https")
      {
          var context = new FakeContext();
          context.Request.Path = path;
          context.Request.Scheme = scheme;
          try
          {
              await Build()(context);
          }
          catch (Exception)
          {
              // Nobody caught the error, so the server answers 500
              context.Response.StatusCode = 500;
          }
          return context;
      }

      private FakeRequestDelegate Build()
      {
          // The end of every pipeline: nobody answered, so 404 Not Found
          FakeRequestDelegate app = context =>
          {
              context.Response.StatusCode = 404;
              return Task.CompletedTask;
          };
          for (int i = steps.Count - 1; i >= 0; i--)
          {
              app = steps[i](app);
          }
          return app;
      }
}
`,
  }}
/>

- Code **before** `await next()` runs on the way **in**. Code **after** it runs on the way **out**.
- `app.Run(...)` with a handler adds an endpoint. `app.Run()` with nothing starts the server. Same name, two different jobs.

## Middleware Execution Order

- Middleware run **in the order you add them** on the way in.
- On the way out, they run in **reverse** order, like taking off layers of clothes.
- So the **first** middleware sees the request first and the response last. That is why the error catcher comes first: it wraps everything after it.

<figure className="blz-fig">
<svg viewBox="0 0 640 230" role="img" aria-labelledby="fig-mw-order">
  <title id="fig-mw-order">Animation: three nested boxes, Middleware A outside, B inside it, C inside B, and the endpoint in the middle. A dot goes down through A, B and C on the left (before next), crosses the endpoint, and comes back up through C, B and A on the right (after next).</title>
  <defs><marker id="fig-mw-order-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="pur" x="20" y="30" width="600" height="190" rx="14" />
  <text className="t m" x="36" y="50" style={{ fontSize: 12, fontWeight: 700 }}>Middleware A</text>
  <rect className="blu" x="70" y="60" width="500" height="150" rx="12" />
  <text className="t m" x="86" y="80" style={{ fontSize: 12, fontWeight: 700 }}>Middleware B</text>
  <rect className="org" x="120" y="90" width="400" height="110" rx="10" />
  <text className="t m" x="136" y="108" style={{ fontSize: 12, fontWeight: 700 }}>Middleware C</text>
  <rect className="grn" x="220" y="117" width="200" height="45" rx="8" />
  <text className="t m" x="320" y="144" textAnchor="middle" style={{ fontSize: 12 }}>Endpoint</text>
  <text className="t" x="170" y="190" textAnchor="middle" style={{ fontSize: 11 }}>in: A, B, C</text>
  <text className="t" x="470" y="190" textAnchor="middle" style={{ fontSize: 11 }}>out: C, B, A</text>
  <path className="line" d="M170 10 V135" markerEnd="url(#fig-mw-order-a)" />
  <path className="line" d="M470 135 V14" markerEnd="url(#fig-mw-order-a)" />
  <circle r="7" style={{ fill: "#7c3aed" }}>
    <animate attributeName="cx" values="170;170;470;470;470" keyTimes="0;0.4;0.6;0.95;1" dur="6s" repeatCount="indefinite" />
    <animate attributeName="cy" values="10;140;140;10;10" keyTimes="0;0.4;0.6;0.95;1" dur="6s" repeatCount="indefinite" />
  </circle>
</svg>
<figcaption>Each middleware wraps the ones after it. In: A, B, C. Out: C, B, A.</figcaption>
</figure>

In the below example, three middleware write a line before and after `next()`. Click **Send /** and read the order. Then move the `C` block above `A` and run it again.

<p>Status: @status</p>
<p>Body: @body</p>
<ol>
      @foreach (var line in log)
      {
          <li>@line</li>
      }
</ol>

@code {
      private List<string> log = new();
      private int status;
      private string body = "";

      private async Task Send(string path)
      {
          log.Clear();
          var app = new FakePipeline();

          app.Use(async (context, next) =>
          {
              log.Add("A: before next");
              await next();
              log.Add("A: after next");
          });

          app.Use(async (context, next) =>
          {
              log.Add("B: before next");
              await next();
              log.Add("B: after next");
          });

          app.Use(async (context, next) =>
          {
              log.Add("C: before next");
              await next();
              log.Add("C: after next");
          });

          app.Run(async context =>
          {
              log.Add("Endpoint");
              await context.Response.WriteAsync("Done");
          });

          var result = await app.SendAsync(path);
          status = result.Response.StatusCode;
          body = result.Response.Body;
      }
}
`,
    "Pipeline/FakePipeline.cs": `namespace BlazorApp.Pipeline;

// A small stand-in for the ASP.NET Core pipeline, so the code boxes can run.
// The method names match the real ones you write in Program.cs.
public delegate Task FakeRequestDelegate(FakeContext context);

public class FakeContext
{
      public FakeRequest Request { get; } = new();
      public FakeResponse Response { get; } = new();
}

public class FakeRequest
{
      public string Method { get; set; } = "GET";
      public string Scheme { get; set; } = "https";
      public string Path { get; set; } = "/";
}

public class FakeResponse
{
      public int StatusCode { get; set; } = 200;
      public Dictionary<string, string> Headers { get; } = new();
      public string Body { get; set; } = "";
      public bool HasStarted => Body != "";

      public Task WriteAsync(string text)
      {
          Body += text;
          return Task.CompletedTask;
      }
}

public class FakePipeline
{
      private readonly List<Func<FakeRequestDelegate, FakeRequestDelegate>> steps = new();

      // The files in wwwroot
      public List<string> WwwRoot { get; } = new() { "/app.css", "/favicon.png" };

      // app.Use: run code, then call next() to pass the request on
      public void Use(Func<FakeContext, Func<Task>, Task> middleware) =>
          steps.Add(next => context => middleware(context, () => next(context)));

      // app.Run: the end of the pipeline. There is no next.
      public void Run(FakeRequestDelegate handler) =>
          steps.Add(_ => handler);

      // app.Map: a separate branch for paths that start with pathStart
      public void Map(string pathStart, Action<FakePipeline> configure)
      {
          var branch = new FakePipeline();
          configure(branch);
          steps.Add(next => async context =>
          {
              var path = context.Request.Path;
              if (path == pathStart || path.StartsWith(pathStart + "/"))
              {
                  context.Request.Path = path.Length > pathStart.Length ? path[pathStart.Length..] : "/";
                  await branch.Build()(context);
              }
              else
              {
                  await next(context);
              }
          });
      }

      // app.UseMiddleware<T>: T has a constructor that takes next,
      // and an InvokeAsync(context) method
      public void UseMiddleware<T>() => steps.Add(next =>
      {
          var middleware = Activator.CreateInstance(typeof(T), next)!;
          var invoke = typeof(T).GetMethod("InvokeAsync")!;
          return context => (Task)invoke.Invoke(middleware, new object[] { context })!;
      });

      // Built-in middleware, cut down to their main job
      public void UseHttpsRedirection() => Use(async (context, next) =>
      {
          if (context.Request.Scheme == "http")
          {
              context.Response.StatusCode = 307;
              context.Response.Headers["Location"] = "https://localhost" + context.Request.Path;
              return;
          }
          await next();
      });

      public void UseExceptionHandler(string errorPath) => Use(async (context, next) =>
      {
          try
          {
              await next();
          }
          catch (Exception)
          {
              context.Response.StatusCode = 500;
              context.Response.Body = "";
              context.Request.Path = errorPath;
              await next();
          }
      });

      public void UseStatusCodePagesWithReExecute(string pagePath) => Use(async (context, next) =>
      {
          await next();
          var code = context.Response.StatusCode;
          if (code >= 400 && !context.Response.HasStarted)
          {
              context.Request.Path = pagePath;
              await next();
              context.Response.StatusCode = code;
          }
      });

      public void MapStaticAssets() => Use(async (context, next) =>
      {
          if (WwwRoot.Contains(context.Request.Path))
          {
              await context.Response.WriteAsync("(the file " + context.Request.Path + ")");
              return;
          }
          await next();
      });

      // Sends one pretend request through the pipeline
      public async Task<FakeContext> SendAsync(string path, string scheme = "https")
      {
          var context = new FakeContext();
          context.Request.Path = path;
          context.Request.Scheme = scheme;
          try
          {
              await Build()(context);
          }
          catch (Exception)
          {
              // Nobody caught the error, so the server answers 500
              context.Response.StatusCode = 500;
          }
          return context;
      }

      private FakeRequestDelegate Build()
      {
          // The end of every pipeline: nobody answered, so 404 Not Found
          FakeRequestDelegate app = context =>
          {
              context.Response.StatusCode = 404;
              return Task.CompletedTask;
          };
          for (int i = steps.Count - 1; i >= 0; i--)
          {
              app = steps[i](app);
          }
          return app;
      }
}
`,
  }}
/>

Order is a common source of bugs. For example, if the error catcher is added **after** the middleware that fails, it never sees the error. Keep the order of the template.

## Built-in Middleware

ASP.NET Core comes with ready-made middleware. You only add one line for each. These are the ones in every Blazor app:

| Middleware | Its job |
|---|---|
| `MapStaticAssets` | Sends files from `wwwroot` (CSS, images, JavaScript) |
| `UseHttpsRedirection` | Moves visitors from `http://` to `https://` |
| `UseExceptionHandler` | Catches errors and shows a friendly error page |
| `UseStatusCodePagesWithReExecute` | Shows a page for answers like 404 Not Found |

### Static Files (MapStaticAssets)

- A **static file** is a file sent exactly as it is, with no code running: `app.css`, `favicon.png`, a `.js` file.
- `app.MapStaticAssets()` serves every file in the **`wwwroot`** folder. For `/app.css`, it sends the file and the request goes no further.
- It also helps speed: files are compressed (made smaller) and the browser is told how long it may keep them.

### HTTPS Redirection (UseHttpsRedirection)

- **HTTPS** is the secure version of HTTP. The data is **encrypted**: scrambled, so others on the network cannot read it.
- `app.UseHttpsRedirection()` answers an `http://` request with status **307** and a **`Location`** header that points to the `https://` address. The browser then asks again, securely.
- A **header** is a small extra line of information on a request or response, like a label on a parcel. `Location` says "go here instead".

### Exception Handling (UseExceptionHandler)

- An **exception** is an error that stops the code, like `throw new Exception(...)`.
- `app.UseExceptionHandler("/Error")` catches exceptions from everything after it. It then **re-executes** the request: it sends it through the pipeline again with the path `/Error`, so the user sees your friendly error page with status **500**.
- The template adds it only **outside Development**. While you develop, you see the full error details instead.

### Status Code Pages (UseStatusCodePagesWithReExecute)

- Some answers have a status code like **404** but no body, so the browser shows an empty page.
- `app.UseStatusCodePagesWithReExecute("/not-found")` runs **after** `next()`. If the status is 400 or higher and nothing was written, it re-executes the request with the path `/not-found`. The status code stays **404**.

In the below example, the four built-in middleware are in a pretend pipeline. The `app.Run` step plays the part of your Blazor pages. Click each button and compare the status and body.

<button @onclick='() => Send("/app.css")'>/app.css</button>
<button @onclick='() => Send("/")'>/</button>
<button @onclick='() => Send("/boom")'>/boom</button>
<button @onclick='() => Send("/missing")'>/missing</button>

<p>Status: @status</p>
<p>Location: @location</p>
<p>Body: @body</p>

@code {
      private int status;
      private string location = "";
      private string body = "";

      private async Task Send(string path, string scheme = "https")
      {
          var app = new FakePipeline();

          app.UseExceptionHandler("/Error");
          app.UseStatusCodePagesWithReExecute("/not-found");
          app.UseHttpsRedirection();
          app.MapStaticAssets();

          // Plays the part of your Blazor pages
          app.Run(async context =>
          {
              switch (context.Request.Path)
              {
                  case "/":
                      await context.Response.WriteAsync("Home page");
                      break;
                  case "/boom":
                      throw new InvalidOperationException("Something broke");
                  case "/Error":
                      await context.Response.WriteAsync("Sorry, something went wrong.");
                      break;
                  case "/not-found":
                      await context.Response.WriteAsync("Sorry, that page does not exist.");
                      break;
                  default:
                      context.Response.StatusCode = 404;
                      break;
              }
          });

          var result = await app.SendAsync(path, scheme);
          status = result.Response.StatusCode;
          location = result.Response.Headers.GetValueOrDefault("Location", "");
          body = result.Response.Body;
      }
}
`,
    "Pipeline/FakePipeline.cs": `namespace BlazorApp.Pipeline;

// A small stand-in for the ASP.NET Core pipeline, so the code boxes can run.
// The method names match the real ones you write in Program.cs.
public delegate Task FakeRequestDelegate(FakeContext context);

public class FakeContext
{
      public FakeRequest Request { get; } = new();
      public FakeResponse Response { get; } = new();
}

public class FakeRequest
{
      public string Method { get; set; } = "GET";
      public string Scheme { get; set; } = "https";
      public string Path { get; set; } = "/";
}

public class FakeResponse
{
      public int StatusCode { get; set; } = 200;
      public Dictionary<string, string> Headers { get; } = new();
      public string Body { get; set; } = "";
      public bool HasStarted => Body != "";

      public Task WriteAsync(string text)
      {
          Body += text;
          return Task.CompletedTask;
      }
}

public class FakePipeline
{
      private readonly List<Func<FakeRequestDelegate, FakeRequestDelegate>> steps = new();

      // The files in wwwroot
      public List<string> WwwRoot { get; } = new() { "/app.css", "/favicon.png" };

      // app.Use: run code, then call next() to pass the request on
      public void Use(Func<FakeContext, Func<Task>, Task> middleware) =>
          steps.Add(next => context => middleware(context, () => next(context)));

      // app.Run: the end of the pipeline. There is no next.
      public void Run(FakeRequestDelegate handler) =>
          steps.Add(_ => handler);

      // app.Map: a separate branch for paths that start with pathStart
      public void Map(string pathStart, Action<FakePipeline> configure)
      {
          var branch = new FakePipeline();
          configure(branch);
          steps.Add(next => async context =>
          {
              var path = context.Request.Path;
              if (path == pathStart || path.StartsWith(pathStart + "/"))
              {
                  context.Request.Path = path.Length > pathStart.Length ? path[pathStart.Length..] : "/";
                  await branch.Build()(context);
              }
              else
              {
                  await next(context);
              }
          });
      }

      // app.UseMiddleware<T>: T has a constructor that takes next,
      // and an InvokeAsync(context) method
      public void UseMiddleware<T>() => steps.Add(next =>
      {
          var middleware = Activator.CreateInstance(typeof(T), next)!;
          var invoke = typeof(T).GetMethod("InvokeAsync")!;
          return context => (Task)invoke.Invoke(middleware, new object[] { context })!;
      });

      // Built-in middleware, cut down to their main job
      public void UseHttpsRedirection() => Use(async (context, next) =>
      {
          if (context.Request.Scheme == "http")
          {
              context.Response.StatusCode = 307;
              context.Response.Headers["Location"] = "https://localhost" + context.Request.Path;
              return;
          }
          await next();
      });

      public void UseExceptionHandler(string errorPath) => Use(async (context, next) =>
      {
          try
          {
              await next();
          }
          catch (Exception)
          {
              context.Response.StatusCode = 500;
              context.Response.Body = "";
              context.Request.Path = errorPath;
              await next();
          }
      });

      public void UseStatusCodePagesWithReExecute(string pagePath) => Use(async (context, next) =>
      {
          await next();
          var code = context.Response.StatusCode;
          if (code >= 400 && !context.Response.HasStarted)
          {
              context.Request.Path = pagePath;
              await next();
              context.Response.StatusCode = code;
          }
      });

      public void MapStaticAssets() => Use(async (context, next) =>
      {
          if (WwwRoot.Contains(context.Request.Path))
          {
              await context.Response.WriteAsync("(the file " + context.Request.Path + ")");
              return;
          }
          await next();
      });

      // Sends one pretend request through the pipeline
      public async Task<FakeContext> SendAsync(string path, string scheme = "https")
      {
          var context = new FakeContext();
          context.Request.Path = path;
          context.Request.Scheme = scheme;
          try
          {
              await Build()(context);
          }
          catch (Exception)
          {
              // Nobody caught the error, so the server answers 500
              context.Response.StatusCode = 500;
          }
          return context;
      }

      private FakeRequestDelegate Build()
      {
          // The end of every pipeline: nobody answered, so 404 Not Found
          FakeRequestDelegate app = context =>
          {
              context.Response.StatusCode = 404;
              return Task.CompletedTask;
          };
          for (int i = steps.Count - 1; i >= 0; i--)
          {
              app = steps[i](app);
          }
          return app;
      }
}
`,
  }}
/>

- `/boom` throws an error, but the user gets the friendly `/Error` page with status 500.
- `/missing` has no page, so the user gets the `/not-found` page with status 404.
- Try removing `app.UseExceptionHandler("/Error");` and click `/boom` again: you get a bare 500 with no body.

## Use, Run and Map

Three methods add steps to the pipeline:

| Method | What it adds | Calls next? |
|---|---|---|
| `app.Use(...)` | Middleware that does something and passes the request on | Yes, usually |
| `app.Run(...)` | The **last** step. It always answers. | No, there is no next |
| `app.Map("/path", ...)` | A **branch**: a separate small pipeline for paths that start with `/path` | Only inside the branch |

- A **branch** is like a side road. Requests for `/admin` turn off into it. All others go straight on.
- Inside the branch, the `/admin` part is taken off the path. So `/admin/orders` is seen as `/orders`.

<figure className="blz-fig">
<svg viewBox="0 0 640 215" role="img" aria-labelledby="fig-mw-map">
  <title id="fig-mw-map">A main road of middleware. At a fork labelled Map /admin, requests that start with /admin turn into a side branch with its own Run step, Admin area. All other requests go straight on to the main Run step, Main shop.</title>
  <defs><marker id="fig-mw-map-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="blu" x="10" y="45" width="90" height="60" rx="10" />
  <text className="t m" x="55" y="80" textAnchor="middle" style={{ fontSize: 12 }}>Request</text>
  <rect className="pur" x="130" y="45" width="110" height="60" rx="10" />
  <text className="t m" x="185" y="72" textAnchor="middle" style={{ fontSize: 12 }}>Use</text>
  <text className="t" x="185" y="90" textAnchor="middle" style={{ fontSize: 11 }}>logger</text>
  <rect className="org" x="270" y="45" width="120" height="60" rx="10" />
  <text className="t m" x="330" y="72" textAnchor="middle" style={{ fontSize: 12 }}>Map</text>
  <text className="t" x="330" y="90" textAnchor="middle" style={{ fontSize: 11 }}>/admin?</text>
  <rect className="grn" x="460" y="45" width="170" height="60" rx="10" />
  <text className="t m" x="545" y="72" textAnchor="middle" style={{ fontSize: 12 }}>Run</text>
  <text className="t" x="545" y="90" textAnchor="middle" style={{ fontSize: 11 }}>Main shop</text>
  <rect className="grn" x="460" y="140" width="170" height="60" rx="10" />
  <text className="t m" x="545" y="167" textAnchor="middle" style={{ fontSize: 12 }}>Run (branch)</text>
  <text className="t" x="545" y="185" textAnchor="middle" style={{ fontSize: 11 }}>Admin area</text>
  <path className="line" d="M100 75 H126" markerEnd="url(#fig-mw-map-a)" />
  <path className="line" d="M240 75 H266" markerEnd="url(#fig-mw-map-a)" />
  <path className="line" d="M390 75 H456" markerEnd="url(#fig-mw-map-a)" />
  <path className="line" d="M330 105 V170 H456" markerEnd="url(#fig-mw-map-a)" />
  <text className="t" x="425" y="68" textAnchor="middle" style={{ fontSize: 10 }}>other paths</text>
  <text className="t" x="392" y="162" textAnchor="middle" style={{ fontSize: 10 }}>/admin...</text>
</svg>
<figcaption>Map sends matching requests down their own branch.</figcaption>
</figure>

In the below example, `Map("/admin", ...)` adds a branch. Click each button and look at the body and the path the branch sees.

<button @onclick='() => Send("/admin")'>/admin</button>
<button @onclick='() => Send("/admin/orders")'>/admin/orders</button>

<p>Status: @status</p>
<p>Body: @body</p>
<ol>
      @foreach (var line in log)
      {
          <li>@line</li>
      }
</ol>

@code {
      private List<string> log = new();
      private int status;
      private string body = "";

      private async Task Send(string path)
      {
          log.Clear();
          var app = new FakePipeline();

          app.Use(async (context, next) =>
          {
              log.Add("Logger: " + context.Request.Path);
              await next();
          });

          app.Map("/admin", admin =>
          {
              admin.Run(async context =>
              {
                  log.Add("Admin branch sees the path " + context.Request.Path);
                  await context.Response.WriteAsync("Admin area");
              });
          });

          app.Run(async context =>
          {
              log.Add("Main Run");
              await context.Response.WriteAsync("Main shop");
          });

          var result = await app.SendAsync(path);
          status = result.Response.StatusCode;
          body = result.Response.Body;
      }
}
`,
    "Pipeline/FakePipeline.cs": `namespace BlazorApp.Pipeline;

// A small stand-in for the ASP.NET Core pipeline, so the code boxes can run.
// The method names match the real ones you write in Program.cs.
public delegate Task FakeRequestDelegate(FakeContext context);

public class FakeContext
{
      public FakeRequest Request { get; } = new();
      public FakeResponse Response { get; } = new();
}

public class FakeRequest
{
      public string Method { get; set; } = "GET";
      public string Scheme { get; set; } = "https";
      public string Path { get; set; } = "/";
}

public class FakeResponse
{
      public int StatusCode { get; set; } = 200;
      public Dictionary<string, string> Headers { get; } = new();
      public string Body { get; set; } = "";
      public bool HasStarted => Body != "";

      public Task WriteAsync(string text)
      {
          Body += text;
          return Task.CompletedTask;
      }
}

public class FakePipeline
{
      private readonly List<Func<FakeRequestDelegate, FakeRequestDelegate>> steps = new();

      // The files in wwwroot
      public List<string> WwwRoot { get; } = new() { "/app.css", "/favicon.png" };

      // app.Use: run code, then call next() to pass the request on
      public void Use(Func<FakeContext, Func<Task>, Task> middleware) =>
          steps.Add(next => context => middleware(context, () => next(context)));

      // app.Run: the end of the pipeline. There is no next.
      public void Run(FakeRequestDelegate handler) =>
          steps.Add(_ => handler);

      // app.Map: a separate branch for paths that start with pathStart
      public void Map(string pathStart, Action<FakePipeline> configure)
      {
          var branch = new FakePipeline();
          configure(branch);
          steps.Add(next => async context =>
          {
              var path = context.Request.Path;
              if (path == pathStart || path.StartsWith(pathStart + "/"))
              {
                  context.Request.Path = path.Length > pathStart.Length ? path[pathStart.Length..] : "/";
                  await branch.Build()(context);
              }
              else
              {
                  await next(context);
              }
          });
      }

      // app.UseMiddleware<T>: T has a constructor that takes next,
      // and an InvokeAsync(context) method
      public void UseMiddleware<T>() => steps.Add(next =>
      {
          var middleware = Activator.CreateInstance(typeof(T), next)!;
          var invoke = typeof(T).GetMethod("InvokeAsync")!;
          return context => (Task)invoke.Invoke(middleware, new object[] { context })!;
      });

      // Built-in middleware, cut down to their main job
      public void UseHttpsRedirection() => Use(async (context, next) =>
      {
          if (context.Request.Scheme == "http")
          {
              context.Response.StatusCode = 307;
              context.Response.Headers["Location"] = "https://localhost" + context.Request.Path;
              return;
          }
          await next();
      });

      public void UseExceptionHandler(string errorPath) => Use(async (context, next) =>
      {
          try
          {
              await next();
          }
          catch (Exception)
          {
              context.Response.StatusCode = 500;
              context.Response.Body = "";
              context.Request.Path = errorPath;
              await next();
          }
      });

      public void UseStatusCodePagesWithReExecute(string pagePath) => Use(async (context, next) =>
      {
          await next();
          var code = context.Response.StatusCode;
          if (code >= 400 && !context.Response.HasStarted)
          {
              context.Request.Path = pagePath;
              await next();
              context.Response.StatusCode = code;
          }
      });

      public void MapStaticAssets() => Use(async (context, next) =>
      {
          if (WwwRoot.Contains(context.Request.Path))
          {
              await context.Response.WriteAsync("(the file " + context.Request.Path + ")");
              return;
          }
          await next();
      });

      // Sends one pretend request through the pipeline
      public async Task<FakeContext> SendAsync(string path, string scheme = "https")
      {
          var context = new FakeContext();
          context.Request.Path = path;
          context.Request.Scheme = scheme;
          try
          {
              await Build()(context);
          }
          catch (Exception)
          {
              // Nobody caught the error, so the server answers 500
              context.Response.StatusCode = 500;
          }
          return context;
      }

      private FakeRequestDelegate Build()
      {
          // The end of every pipeline: nobody answered, so 404 Not Found
          FakeRequestDelegate app = context =>
          {
              context.Response.StatusCode = 404;
              return Task.CompletedTask;
          };
          for (int i = steps.Count - 1; i >= 0; i--)
          {
              app = steps[i](app);
          }
          return app;
      }
}
`,
  }}
/>

Anything added **after** `app.Run(...)` never runs, because `Run` does not call `next`. Keep `Run` at the end.

## Short-Circuiting the Pipeline

- **Short-circuiting** means a middleware answers by itself and does **not** call `next()`. The rest of the pipeline never runs.
- It is useful when the answer is already clear: a static file was found, the user is not allowed in, or the shop is closed for maintenance.
- It also saves work, because the page code does not run at all.

<figure className="blz-fig">
<svg viewBox="0 0 640 185" role="img" aria-labelledby="fig-mw-short">
  <title id="fig-mw-short">Animation: a request passes the first middleware, reaches the second middleware, Closed?, and turns back at once with 503. The third middleware and the endpoint are greyed out because they never run.</title>
  <defs><marker id="fig-mw-short-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="blu" x="10" y="50" width="90" height="90" rx="12" />
  <text className="t m" x="55" y="100" textAnchor="middle" style={{ fontSize: 12, fontWeight: 700 }}>Browser</text>
  <rect className="pur" x="130" y="40" width="100" height="110" rx="12" />
  <text className="t m" x="180" y="100" textAnchor="middle" style={{ fontSize: 12 }}>Logger</text>
  <rect className="org" x="250" y="40" width="100" height="110" rx="12" />
  <text className="t m" x="300" y="92" textAnchor="middle" style={{ fontSize: 12 }}>Closed?</text>
  <text className="t" x="300" y="110" textAnchor="middle" style={{ fontSize: 11 }}>answers 503</text>
  <g style={{ opacity: 0.35 }}>
    <rect className="pur" x="370" y="40" width="100" height="110" rx="12" />
    <text className="t m" x="420" y="100" textAnchor="middle" style={{ fontSize: 12 }}>More...</text>
    <rect className="grn" x="500" y="50" width="130" height="90" rx="12" />
    <text className="t m" x="565" y="100" textAnchor="middle" style={{ fontSize: 12 }}>Endpoint</text>
  </g>
  <path className="line" d="M100 62 H296" markerEnd="url(#fig-mw-short-a)" />
  <path className="line" d="M300 128 H104" markerEnd="url(#fig-mw-short-a)" />
  <text className="t m" x="440" y="172" textAnchor="middle" style={{ fontSize: 11 }}>never reached</text>
  <circle r="7" style={{ fill: "#7c3aed" }}>
    <animate attributeName="cx" values="100;300;300;100;100" keyTimes="0;0.4;0.5;0.9;1" dur="5s" repeatCount="indefinite" />
    <animate attributeName="cy" values="62;62;128;128;128" keyTimes="0;0.4;0.5;0.9;1" dur="5s" repeatCount="indefinite" />
  </circle>
</svg>
<figcaption>The second middleware answers by itself. Nothing after it runs.</figcaption>
</figure>

In the below example, a middleware checks a **closed** switch. When it is on, the middleware answers **503 Service Unavailable** and returns without calling `next()`. Tick the box, click **Send /** and look at the log.

<button @onclick='() => Send("/")'>Send /</button>

<p>Status: @status</p>
<p>Body: @body</p>
<ol>
      @foreach (var line in log)
      {
          <li>@line</li>
      }
</ol>

@code {
      private bool closed;
      private List<string> log = new();
      private int status;
      private string body = "";

      private async Task Send(string path)
      {
          log.Clear();
          var app = new FakePipeline();

          app.Use(async (context, next) =>
          {
              log.Add("Logger: request in");
              await next();
              log.Add("Logger: response out");
          });

          app.Use(async (context, next) =>
          {
              if (closed)
              {
                  log.Add("Closed check: answering by myself");
                  context.Response.StatusCode = 503;
                  await context.Response.WriteAsync("Back soon!");
                  return;   // no next(): the short-circuit
              }
              await next();
          });

          app.Run(async context =>
          {
              log.Add("Endpoint");
              await context.Response.WriteAsync("Welcome to the Tea Shop");
          });

          var result = await app.SendAsync(path);
          status = result.Response.StatusCode;
          body = result.Response.Body;
      }
}
`,
    "Pipeline/FakePipeline.cs": `namespace BlazorApp.Pipeline;

// A small stand-in for the ASP.NET Core pipeline, so the code boxes can run.
// The method names match the real ones you write in Program.cs.
public delegate Task FakeRequestDelegate(FakeContext context);

public class FakeContext
{
      public FakeRequest Request { get; } = new();
      public FakeResponse Response { get; } = new();
}

public class FakeRequest
{
      public string Method { get; set; } = "GET";
      public string Scheme { get; set; } = "https";
      public string Path { get; set; } = "/";
}

public class FakeResponse
{
      public int StatusCode { get; set; } = 200;
      public Dictionary<string, string> Headers { get; } = new();
      public string Body { get; set; } = "";
      public bool HasStarted => Body != "";

      public Task WriteAsync(string text)
      {
          Body += text;
          return Task.CompletedTask;
      }
}

public class FakePipeline
{
      private readonly List<Func<FakeRequestDelegate, FakeRequestDelegate>> steps = new();

      // The files in wwwroot
      public List<string> WwwRoot { get; } = new() { "/app.css", "/favicon.png" };

      // app.Use: run code, then call next() to pass the request on
      public void Use(Func<FakeContext, Func<Task>, Task> middleware) =>
          steps.Add(next => context => middleware(context, () => next(context)));

      // app.Run: the end of the pipeline. There is no next.
      public void Run(FakeRequestDelegate handler) =>
          steps.Add(_ => handler);

      // app.Map: a separate branch for paths that start with pathStart
      public void Map(string pathStart, Action<FakePipeline> configure)
      {
          var branch = new FakePipeline();
          configure(branch);
          steps.Add(next => async context =>
          {
              var path = context.Request.Path;
              if (path == pathStart || path.StartsWith(pathStart + "/"))
              {
                  context.Request.Path = path.Length > pathStart.Length ? path[pathStart.Length..] : "/";
                  await branch.Build()(context);
              }
              else
              {
                  await next(context);
              }
          });
      }

      // app.UseMiddleware<T>: T has a constructor that takes next,
      // and an InvokeAsync(context) method
      public void UseMiddleware<T>() => steps.Add(next =>
      {
          var middleware = Activator.CreateInstance(typeof(T), next)!;
          var invoke = typeof(T).GetMethod("InvokeAsync")!;
          return context => (Task)invoke.Invoke(middleware, new object[] { context })!;
      });

      // Built-in middleware, cut down to their main job
      public void UseHttpsRedirection() => Use(async (context, next) =>
      {
          if (context.Request.Scheme == "http")
          {
              context.Response.StatusCode = 307;
              context.Response.Headers["Location"] = "https://localhost" + context.Request.Path;
              return;
          }
          await next();
      });

      public void UseExceptionHandler(string errorPath) => Use(async (context, next) =>
      {
          try
          {
              await next();
          }
          catch (Exception)
          {
              context.Response.StatusCode = 500;
              context.Response.Body = "";
              context.Request.Path = errorPath;
              await next();
          }
      });

      public void UseStatusCodePagesWithReExecute(string pagePath) => Use(async (context, next) =>
      {
          await next();
          var code = context.Response.StatusCode;
          if (code >= 400 && !context.Response.HasStarted)
          {
              context.Request.Path = pagePath;
              await next();
              context.Response.StatusCode = code;
          }
      });

      public void MapStaticAssets() => Use(async (context, next) =>
      {
          if (WwwRoot.Contains(context.Request.Path))
          {
              await context.Response.WriteAsync("(the file " + context.Request.Path + ")");
              return;
          }
          await next();
      });

      // Sends one pretend request through the pipeline
      public async Task<FakeContext> SendAsync(string path, string scheme = "https")
      {
          var context = new FakeContext();
          context.Request.Path = path;
          context.Request.Scheme = scheme;
          try
          {
              await Build()(context);
          }
          catch (Exception)
          {
              // Nobody caught the error, so the server answers 500
              context.Response.StatusCode = 500;
          }
          return context;
      }

      private FakeRequestDelegate Build()
      {
          // The end of every pipeline: nobody answered, so 404 Not Found
          FakeRequestDelegate app = context =>
          {
              context.Response.StatusCode = 404;
              return Task.CompletedTask;
          };
          for (int i = steps.Count - 1; i >= 0; i--)
          {
              app = steps[i](app);
          }
          return app;
      }
}
`,
  }}
/>

- With the box ticked, the log has no "Endpoint" line. The logger still writes its "out" line, because the response passes back through it.
- `MapStaticAssets` and `UseHttpsRedirection` short-circuit in the same way.

## Creating Custom Middleware

You can write your own middleware in two ways: **inline**, as a lambda inside `Program.cs`, or as a **class** in its own file.

### Inline Middleware

- **Inline** means the code is written right where it is used, as a **lambda**: a small unnamed method, `(context, next) => { ... }`.
- It is good for short jobs. All the `app.Use(...)` examples above were inline.

This is how a real inline middleware looks in `Program.cs`. It measures how long each request takes:

{
      var watch = System.Diagnostics.Stopwatch.StartNew();
      await next(context);
      watch.Stop();
      app.Logger.LogInformation("{Path} took {Ms} ms",
          context.Request.Path, watch.ElapsedMilliseconds);
});
`}
/>

- In real code, pass the context on with `next(context)`. Both `next()` and `next(context)` work, but `next(context)` is a little faster.
- `app.Logger` writes to the log, which you see in the terminal where `dotnet run` is running.

### Middleware Classes

When the code grows, move it into a **class**. A middleware class has three parts:

1. A **constructor** that receives `next`, of type **`RequestDelegate`** (a method that handles a request).
2. A method **`InvokeAsync(HttpContext context)`** that does the work and calls `next`.
3. One line in `Program.cs`: **`app.UseMiddleware<T>()`**.

- The class is created **once**, when the app starts. So do not keep per-request data in fields.
- `Interlocked.Increment` adds 1 safely, even when many requests arrive at the same moment.
- The header name starts with `X-`: a common way to mark your own, non-standard headers.

In the below example, the same class uses `FakeRequestDelegate` and `FakeContext`, so it can run here. Click **Send /** a few times and watch the request ID grow.

<p>Status: @status</p>
<p>X-Request-Id: @requestId</p>
<p>Body: @body</p>

@code {
      private int status;
      private string requestId = "";
      private string body = "";

      private async Task Send(string path)
      {
          var app = new FakePipeline();

          app.UseMiddleware<RequestIdMiddleware>();

          app.Run(async context =>
          {
              await context.Response.WriteAsync("Hello from the Tea Shop");
          });

          var result = await app.SendAsync(path);
          status = result.Response.StatusCode;
          requestId = result.Response.Headers["X-Request-Id"];
          body = result.Response.Body;
      }
}
`,
    "Middleware/RequestIdMiddleware.cs": `namespace BlazorApp.Middleware;

using BlazorApp.Pipeline;

public class RequestIdMiddleware
{
      private readonly FakeRequestDelegate next;
      private static int count;

      public RequestIdMiddleware(FakeRequestDelegate next)
      {
          this.next = next;
      }

      public async Task InvokeAsync(FakeContext context)
      {
          var id = Interlocked.Increment(ref count);
          context.Response.Headers["X-Request-Id"] = id.ToString();
          await next(context);
      }
}
`,
    "Pipeline/FakePipeline.cs": `namespace BlazorApp.Pipeline;

// A small stand-in for the ASP.NET Core pipeline, so the code boxes can run.
// The method names match the real ones you write in Program.cs.
public delegate Task FakeRequestDelegate(FakeContext context);

public class FakeContext
{
      public FakeRequest Request { get; } = new();
      public FakeResponse Response { get; } = new();
}

public class FakeRequest
{
      public string Method { get; set; } = "GET";
      public string Scheme { get; set; } = "https";
      public string Path { get; set; } = "/";
}

public class FakeResponse
{
      public int StatusCode { get; set; } = 200;
      public Dictionary<string, string> Headers { get; } = new();
      public string Body { get; set; } = "";
      public bool HasStarted => Body != "";

      public Task WriteAsync(string text)
      {
          Body += text;
          return Task.CompletedTask;
      }
}

public class FakePipeline
{
      private readonly List<Func<FakeRequestDelegate, FakeRequestDelegate>> steps = new();

      // The files in wwwroot
      public List<string> WwwRoot { get; } = new() { "/app.css", "/favicon.png" };

      // app.Use: run code, then call next() to pass the request on
      public void Use(Func<FakeContext, Func<Task>, Task> middleware) =>
          steps.Add(next => context => middleware(context, () => next(context)));

      // app.Run: the end of the pipeline. There is no next.
      public void Run(FakeRequestDelegate handler) =>
          steps.Add(_ => handler);

      // app.Map: a separate branch for paths that start with pathStart
      public void Map(string pathStart, Action<FakePipeline> configure)
      {
          var branch = new FakePipeline();
          configure(branch);
          steps.Add(next => async context =>
          {
              var path = context.Request.Path;
              if (path == pathStart || path.StartsWith(pathStart + "/"))
              {
                  context.Request.Path = path.Length > pathStart.Length ? path[pathStart.Length..] : "/";
                  await branch.Build()(context);
              }
              else
              {
                  await next(context);
              }
          });
      }

      // app.UseMiddleware<T>: T has a constructor that takes next,
      // and an InvokeAsync(context) method
      public void UseMiddleware<T>() => steps.Add(next =>
      {
          var middleware = Activator.CreateInstance(typeof(T), next)!;
          var invoke = typeof(T).GetMethod("InvokeAsync")!;
          return context => (Task)invoke.Invoke(middleware, new object[] { context })!;
      });

      // Built-in middleware, cut down to their main job
      public void UseHttpsRedirection() => Use(async (context, next) =>
      {
          if (context.Request.Scheme == "http")
          {
              context.Response.StatusCode = 307;
              context.Response.Headers["Location"] = "https://localhost" + context.Request.Path;
              return;
          }
          await next();
      });

      public void UseExceptionHandler(string errorPath) => Use(async (context, next) =>
      {
          try
          {
              await next();
          }
          catch (Exception)
          {
              context.Response.StatusCode = 500;
              context.Response.Body = "";
              context.Request.Path = errorPath;
              await next();
          }
      });

      public void UseStatusCodePagesWithReExecute(string pagePath) => Use(async (context, next) =>
      {
          await next();
          var code = context.Response.StatusCode;
          if (code >= 400 && !context.Response.HasStarted)
          {
              context.Request.Path = pagePath;
              await next();
              context.Response.StatusCode = code;
          }
      });

      public void MapStaticAssets() => Use(async (context, next) =>
      {
          if (WwwRoot.Contains(context.Request.Path))
          {
              await context.Response.WriteAsync("(the file " + context.Request.Path + ")");
              return;
          }
          await next();
      });

      // Sends one pretend request through the pipeline
      public async Task<FakeContext> SendAsync(string path, string scheme = "https")
      {
          var context = new FakeContext();
          context.Request.Path = path;
          context.Request.Scheme = scheme;
          try
          {
              await Build()(context);
          }
          catch (Exception)
          {
              // Nobody caught the error, so the server answers 500
              context.Response.StatusCode = 500;
          }
          return context;
      }

      private FakeRequestDelegate Build()
      {
          // The end of every pipeline: nobody answered, so 404 Not Found
          FakeRequestDelegate app = context =>
          {
              context.Response.StatusCode = 404;
              return Task.CompletedTask;
          };
          for (int i = steps.Count - 1; i >= 0; i--)
          {
              app = steps[i](app);
          }
          return app;
      }
}
`,
  }}
/>
## Common mistakes

<div className="tscroll">

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| Forgetting `await next()` in `app.Use` | The next middleware runs by itself | Call `await next()` unless you mean to stop | The page never runs, and the user gets an empty answer |
| `UseExceptionHandler` added late in the list | Order does not matter | Add it **first**, so it wraps everything | Errors before it are not caught |
| Adding middleware after `app.Run(...)` | Every line runs | Keep `app.Run(...)` as the last step | The middleware after it never runs |
| Writing to the response, then calling `next()` | Two answers can be joined | Either answer and `return`, or call `next()` | Mixed bodies or an error |
| Mixing up `app.Run(handler)` and `app.Run()` | They do the same thing | `Run(handler)` is the last step; `Run()` starts the server | Code that never runs, or an app that does not start |

</div>

## Check Yourself

## Exercises

## What to Remember

- **Middleware** are small pieces of code that every request passes through. Together they form the **request pipeline**, which ends at an **endpoint** such as your Blazor page.
- Set them up in `Program.cs`, after `builder.Build()`. The order of the lines is the order they run in. On the way out, the order is reversed.
- Built-in: `UseExceptionHandler` (first), `UseStatusCodePagesWithReExecute`, `UseHttpsRedirection`, `UseAntiforgery`, `MapStaticAssets` and your pages.
- `Use` passes the request on with `next()`. `Run` is the last step. `Map` makes a branch for one path.
- Not calling `next()` **short-circuits** the pipeline: the middleware answers by itself.
- Write custom middleware inline with `app.Use`, or as a class with a `RequestDelegate` constructor, `InvokeAsync(HttpContext)` and `app.UseMiddleware<T>()`.

Next: **Authentication**
