Student learning series · Lesson 3 of 6
Trace the request pipeline, add a response header, and understand middleware order.
What you will learn
Middleware runs around an endpoint. A component can do work before calling the next component and after it returns. Imagine a visitor passing through an entry desk, a classroom and the exit desk.
1. Create the project
dotnet new web -n MiddlewareLesson
cd MiddlewareLessonReplace Program.cs. Open a second terminal to call the endpoint while the server stays running.
2. Complete Program.cs
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.Use(async (context, next) =>
{
app.Logger.LogInformation("Before endpoint: {Path}", context.Request.Path);
context.Response.Headers["X-Lesson"] = "Middleware";
await next(context);
app.Logger.LogInformation("After endpoint: {Status}", context.Response.StatusCode);
});
app.MapGet("/hello", () => Results.Ok(new { message = "Hello student" }));
app.Run();
3. Run and observe
dotnet run --no-launch-profile -- --urls http://127.0.0.1:5070Stop the server with Ctrl+C before starting the next lesson on the same port. For web lessons, visit the listed GET path at http://127.0.0.1:5070 in your browser. Use an HTTP client for POST, PUT and DELETE with Content-Type: application/json.
GET /hello returns {"message":"Hello student"}.
The response has X-Lesson: Middleware.
The console logs Before endpoint, followed by After endpoint: 200.4. Understand the code
Use registers our middleware before the endpoint. The header is assigned before calling next, because response headers may become read-only once a response starts. await next(context) allows the endpoint to run. Removing it short-circuits the pipeline, so the endpoint does not execute.
Practice exercise
Add a second middleware that logs B before next and B after next. Predict the order when A is registered before B.
Self-check and answer
The order is A before, B before, endpoint, B after, A after. Put exception handling early in a real application. Authentication must precede authorization; middleware order is part of behavior.
Study notes
Type the example yourself, run it, change one behavior, and explain the result in your own words. Keep each lesson in its own project. These examples were compiled with .NET SDK 9.0.306; select a currently supported SDK for new study projects. The course teaches modern .NET and ASP.NET Core, rather than obsolete .NET Core 3.1 or classic Web Forms.
Return to the .NET Core student learning path · Official Microsoft documentation · .NET support policy
No comments:
Post a Comment
Please do not enter any spam link in the comment box.