</>
Skip to content
ASP lessons (35/40)

ASP — ASP.NET Middleware

What is Middleware?

Middleware components handle HTTP requests and responses.

Built-in Middleware

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

Custom Middleware

app.Use(async (context, next) =>
{
    // Before request
    var start = DateTime.Now;
    
    await next();
    
    // After request
    var duration = DateTime.Now - start;
    Console.WriteLine($"Request took {duration.TotalMilliseconds}ms");
});

Middleware Class

public class RequestLoggingMiddleware
{
    private readonly RequestDelegate _next;
    
    public RequestLoggingMiddleware(RequestDelegate next)
    {
        _next = next;
    }
    
    public async Task InvokeAsync(HttpContext context)
    {
        // Before
        Console.WriteLine($"Request: {context.Request.Path}");
        
        await _next(context);
        
        // After
        Console.WriteLine($"Response: {context.Response.StatusCode}");
    }
}

Register Middleware

app.UseMiddleware<RequestLoggingMiddleware>();

Mini Practice

  1. Add built-in middleware
  2. Create custom middleware
  3. Order middleware correctly
  4. Log request information

Up Next

Continue with ASP.NET Authentication — authentication.

Related Topics

Frequently Asked Questions about ASP.NET Middleware

What is ASP.NET Middleware in ASP?

ASP.NET Middleware is a fundamental concept in ASP. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn ASP.NET Middleware?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn ASP.NET Middleware.

Why is ASP.NET Middleware important in ASP?

ASP.NET Middleware is essential for ASP development. Understanding this concept will help you write better code and solve real-world problems more effectively.