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!

➑️ Next:

Learn More About ASP.NET Core πŸš€

What is ASP.NET Core? πŸ‘‰ Explained
ASP.NET Core vs .NET Framework πŸ‘‰ Explained
Role of Kestrel Server in ASP.NET Core πŸ‘‰ Explained
Middleware & Request Pipeline πŸ‘‰ Explained
Dependency Injection in ASP.NET Core πŸ‘‰ Explained
Program.cs vs Startup.cs πŸ‘‰ Explained
Configuration & appsettings.json πŸ‘‰ Explained
Environment-specific settings πŸ‘‰ Explained
Writing Custom Middleware πŸ‘‰ Explained
Logging in ASP.NET Core πŸ‘‰ Explained
Static File Middleware πŸ‘‰ Explained
Routing fundamentals πŸ‘‰ Explained
Model Binding & Validation πŸ‘‰ Explained
Razor Pages vs MVC πŸ‘‰ Explained
Tag Helpers overview πŸ‘‰ Explained
Filters in MVC (Action, Authorization, Exception) πŸ‘‰ Explained
Web API controllers & content negotiation πŸ‘‰ Explained
Versioning ASP.NET Core Web API πŸ‘‰ Explained
Entity Framework Core introduction πŸ‘‰ Explained
Code-First vs Database-First in EF Core πŸ‘‰ Explained
Migrations in EF Core πŸ‘‰ Explained
LINQ fundamentals πŸ‘‰ Explained
Async/Await and async controllers πŸ‘‰ Explained
Error & Exception Handling Middleware πŸ‘‰ Explained
CORS configuration & usage πŸ‘‰ Explained
Authentication vs Authorization πŸ‘‰ Explained
ASP.NET Core Identity basics πŸ‘‰ Explained
JWT Authentication integration πŸ‘‰ Explained
Caching strategies πŸ‘‰ Explained
Session & State Management πŸ‘‰ Explained
File Upload handling πŸ‘‰ Explained
Health Checks & monitoring πŸ‘‰ Explained
Hosted Services & Background Tasks πŸ‘‰ Explained
Working with IWebHostEnvironment πŸ‘‰ Explained
IWebHostBuilder and WebHost vs Generic Host πŸ‘‰ Explained
Deployment to IIS, Kestrel, Nginx, Docker πŸ‘‰ Explained
Use of HTTP.sys Server πŸ‘‰ Explained
Configuration providers (JSON, env, CLI) πŸ‘‰ Explained
Handling Concurrency in EF Core πŸ‘‰ Explained
Model validation & custom validation πŸ‘‰ Explained
Dependency Injection service lifetimes πŸ‘‰ Explained
Security best practices (HTTPS, HSTS, CSP) πŸ‘‰ Explained
Authorization policies & claims πŸ‘‰ Explained
Rate limiting & request throttling πŸ‘‰ Explained
Health & metrics integration πŸ‘‰ Explained
Swagger/OpenAPI documentation πŸ‘‰ Explained
Blazor fundamentals πŸ‘‰ Explained
Razor Class Libraries (RCL) πŸ‘‰ Explained
SignalR real-time communication πŸ‘‰ Explained
Performance optimization & profiling πŸ‘‰ Explained
Share:

Tags:


Feedback Modal Popup