What is Middleware in ASP.NET Core? See Example

Middleware in ASP.NET Core is software that’s assembled into an application pipeline to handle HTTP requests and responses. Each component can process, modify, or short-circuit requests, making it a powerful feature for cross-cutting concerns like authentication, logging, and error handling.

Key Features:

  • Processes HTTP requests and responses
  • Enables logging, authentication, and exception handling
  • Can be added in a specific order in the pipeline
  • Supports custom and built-in middleware
  • Lightweight and modular design

Example:
Adding simple middleware in Program.cs:

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

app.Use(async (context, next) =>
{
    Console.WriteLine("Request Incoming: " + context.Request.Path);
    await next();
    Console.WriteLine("Response Outgoing: " + context.Response.StatusCode);
});

app.MapGet("/", () => "Hello Middleware!");

app.Run();

Middleware is essential in ASP.NET Core for handling cross-cutting tasks efficiently, providing flexibility and control over the request pipeline.

Citations:

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *