Writing Custom Middleware in ASP.NET Core
π‘ Concept Name
Custom Middleware in ASP.NET Core
π Quick Intro
Middleware is software that's assembled into an application pipeline to handle requests and responses. In ASP.NET Core, you can easily write your own custom middleware for logging, security, response modification, and more.
π§ Analogy / Short Story
Imagine a series of airport security checks: ID verification, baggage scan, and metal detector. Each step processes a person and passes them to the next. Middleware in ASP.NET Core acts the sameβeach component in the pipeline can inspect, modify, or halt the HTTP request or response.
π§ Technical Explanation
Middleware in ASP.NET Core is represented by a class with a `Invoke` or `InvokeAsync` method. Each middleware component is added via `app.Use...()` and executed in the order it is added to the request pipeline.
Custom middleware lets you add cross-cutting logic like request logging, authentication, exception handling, and more.
π― Purpose & Use Case
- β Centralized logging of requests/responses
- β Custom authentication/authorization filters
- β Global exception handling and response formatting
- β Modify request/response headers dynamically
- β Measure request duration for performance insights
π» Real Code Example
Example: Custom Middleware for Logging
public class LoggingMiddleware
{
private readonly RequestDelegate _next;
public LoggingMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
Console.WriteLine($"Request: {context.Request.Path}");
await _next(context);
Console.WriteLine($"Response: {context.Response.StatusCode}");
}
}
// Register it in Program.cs or Startup.cs
app.UseMiddleware();

β Interview Q&A
Q1: What is middleware in ASP.NET Core?
A: Middleware is code that handles requests and responses in the pipeline.
Q2: How do you create custom middleware?
A: By creating a class with `InvokeAsync` and registering it via `app.UseMiddleware`.
Q3: Order of middleware execution?
A: Middleware executes in the order they are added to the pipeline.
Q4: Can middleware short-circuit the pipeline?
A: Yes, it can terminate the request before passing to the next component.
Q5: Common use-cases of middleware?
A: Logging, security, error handling, header modification.
Q6: What is the `RequestDelegate`?
A: It represents the next middleware in the pipeline.
Q7: Can middleware access request body?
A: Yes, but reading the body requires buffering it first.
Q8: Can we use DI in middleware constructor?
A: Yes, services can be injected via constructor.
Q9: What if middleware throws exception?
A: Without error handling middleware, it crashes the app.
Q10: Difference between `app.Use` and `app.Run`?
A: `Use` passes to next middleware; `Run` terminates the pipeline.
π MCQs
π MCQs
Q1. What is middleware in ASP.NET Core?
- Routing class
- API controller
- Component in request pipeline
- Database layer
Q2. Which method must custom middleware implement?
- Configure
- Invoke
- InvokeAsync
- Handle
Q3. What is the order of middleware execution?
- Alphabetical
- Reverse
- Random
- As registered in code
Q4. How to register custom middleware?
- services.AddMiddleware
- app.UseMiddleware
- app.Register
- app.ConfigureMiddleware
Q5. What type is RequestDelegate?
- Action
- Func
- Middleware Class
- Delegate for next middleware
Q6. What can middleware access?
- Only request
- Only response
- Neither
- Request and response
Q7. Can middleware halt further execution?
- No
- Only in exceptions
- Yes
- Depends on controller
Q8. Where do you place error handling middleware?
- Anywhere
- Last
- First
- After routing
Q9. Middleware best use-case?
- Building views
- Database update
- Routing
- Logging requests
Q10. What is app.Run used for?
- Starts app
- Adds last middleware
- Logs requests
- Terminates pipeline
π‘ Bonus Insight
Middleware is a foundational concept in ASP.NET Core and mastering it enables clean and scalable architectures. You can even package and reuse custom middleware across multiple projects.
π PDF Download
Need a handy summary for your notes? Download this topic as a PDF!