Middleware handles work in an ASP.NET Core HTTP request pipeline. Each component can pass the request to the next component or end the pipeline by producing a response. Middleware differs from services: services provide application functionality, while middleware handles requests as they pass through the app. section 1.2.2 section 1.3
Register middleware in Program.cs, the app’s entry point. Middleware configuration commonly uses Use, Map, and Run methods; service registration commonly uses Add methods. A potentially terminal component ends a request only when its rules match. A terminal component always ends it. section 1.2.2
var builder = WebApplication.CreateBuilder(args); #1
// Add services to the container.
builder.Services.AddControllers(); #2
// Learn more about configuring Swagger/OpenAPI
// at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer(); #2
builder.Services.AddSwaggerGen(); #2
var app = builder.Build(); #3
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger(); #4
app.UseSwaggerUI(); #4
}
app.UseHttpsRedirection(); #4
app.UseAuthorization(); #4
app.MapControllers(); #4
app.Run(); #5
The starter pipeline enables Swagger in development, adds HTTPS redirection and authorization, maps controllers, then starts the app. section 1.2.2
Give the board-game API a no-cache default
Add custom middleware after app.UseAuthorization() when responses should default to no-cache, no-store. The Use callback sets the cache-control response header, then calls next.Invoke() to continue the pipeline. This is nonblocking middleware: it does not produce the response itself. An endpoint with an explicit ResponseCache directive can override the fallback. section 8.2.2
Listing 8.2 Program.cs file: Custom caching middleware
App.UseAuthorization();
app.Use((context, next) => #1
{
context.Response.Headers["cache-control"] =
"no-cache, no-store";
return next.Invoke();
});
The callback shows the two responsibilities in order: set a response header, then pass control onward with next.Invoke(). section 8.2.2
To check the fallback, run the API in Debug mode and inspect a response without an explicit caching directive for cache-control: no-cache, no-store. Then check a BoardGames GET response with an explicit directive to confirm it takes precedence. Middleware also handles other pipeline work: JWT bearer authentication adds token reading before authorization. section 8.2.2 section 9.2.5









