# Understanding the ASP.NET Core Request Pipeline

Every HTTP request in an ASP.NET Core app flows through something called the **middleware pipeline** and if you understand it, you can unlock *serious* control over how your app behaves.

In this post, I’ll break down what the request pipeline is, how middleware works, and how you can customize it like a pro.

---

## 🧱 What Is Middleware?

Middleware is like a conveyor belt; each step (or middleware) does something to the request, then passes it on.

It can:
- ✅ Authenticate a user
- ✅ Log a request
- ✅ Handle errors
- ✅ Modify the request or response

Each middleware decides whether to:
- Continue to the next step (`await next();`)
- Short-circuit the pipeline and end the response

---

## 🔁 Default Pipeline Example

In a typical `Program.cs`, you'll see:

```csharp
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

app.Run();
```

Each `app.Use...` line is a middleware. They run **in the order** you add them so order matters!

---

## ✍️ Writing Your Own Middleware

Custom middleware is easy to build:

```csharp
public class RequestLoggerMiddleware
{
    private readonly RequestDelegate _next;

    public RequestLoggerMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        Console.WriteLine($"[{DateTime.Now}] Request: {context.Request.Method} {context.Request.Path}");
        await _next(context);
    }
}
```

Register it like this:

```csharp
app.UseMiddleware<RequestLoggerMiddleware>();
```

Boom — you’ve just inserted a custom step into your pipeline.

---

## ⚠️ Common Pitfalls

- 🔁 **Order of middleware matters** (e.g., `UseRouting` must come before `UseEndpoints`)
- 🔒 **Put `UseAuthentication()` before `UseAuthorization()`**
- 🧪 Test your custom middleware in isolation

---

## 💡 Real-World Use Cases

- Logging with Serilog
- Custom exception handling
- Multi-tenancy or per-request headers
- Feature flags

---

## ✅ Up Next

Now that you understand the pipeline, we’ll explore **routing** how your app maps incoming requests to specific logic.

➡️ [Routing in ASP.NET Core Made Easy →](./aspnetcore-routing-guide)

Follow the series to keep getting better, one layer at a time 💪

