中间件顺序与内置中间件
了解身份验证、路由、CORS 和异常处理的正确中间件顺序。
中间件顺序与内置中间件 是 CoddyKit 上的免费 C# Academy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 C# Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 C# Academy 课程共包含 4 节课。
为什么顺序很重要
ASP.NET Core 中间件严格按照注册顺序运行。顺序错误会导致安全漏洞、性能问题或行为异常——例如,路由必须在授权之前运行,而授权必须在端点执行之前运行。
推荐的中间件顺序
微软记录了推荐的顺序。偏离该顺序会产生难以调试的问题。下面是生产环境 ASP.NET Core API 的规范顺序。
// Recommended order:
app.UseExceptionHandler(); // 1. Catch all exceptions
app.UseHsts(); // 2. HTTP Strict Transport Security
app.UseHttpsRedirection(); // 3. Redirect HTTP to HTTPS
app.UseStaticFiles(); // 4. Serve static assets
app.UseRouting(); // 5. Match route patterns
app.UseCors(); // 6. Cross-Origin
app.UseAuthentication(); // 7. Who are you?
app.UseAuthorization(); // 8. Are you allowed?
app.UseRateLimiter(); // 9. Throttle
app.UseOutputCache(); // 10. Cache responses
// Map endpoints here
app.MapControllers();
app.Run();首先处理异常
异常处理中间件必须放在第一位(最外层),这样才能捕获后续所有中间件和端点抛出的异常。
// Development: detailed error page
if (app.Environment.IsDevelopment())
app.UseDeveloperExceptionPage();
else
{
// Production: generic error page + structured response
app.UseExceptionHandler("/error");
app.UseHsts();
}
// OR: use ProblemDetails globally (recommended .NET 8+)
builder.Services.AddProblemDetails();
app.UseExceptionHandler();
// All unhandled exceptions -> RFC 7807 ProblemDetails JSON路由之前提供静态文件
静态文件(UseStaticFiles)应放在路由之前。提供静态文件会让管道短路,因此无需为 /css/main.css 运行身份验证或路由处理。
app.UseStaticFiles(); // serves wwwroot/* without going through auth
app.UseRouting(); // expensive: runs route matching
// If you put UseStaticFiles AFTER UseRouting, the route
// matcher runs unnecessarily for every .js/.css request.
// Serve static files first for better performance.身份验证先于授权
UseAuthentication 必须在 UseAuthorization 之前运行。身份验证会填充 HttpContext.User;授权则根据策略检查已填充的用户。
// WRONG ORDER — authorization runs before user is populated:
app.UseAuthorization(); // user is null → everything allowed!
app.UseAuthentication(); // too late
// CORRECT:
app.UseAuthentication(); // populates context.User
app.UseAuthorization(); // checks context.User against policies身份验证前的 CORS
CORS 中间件必须在身份验证之前运行,这样预检 OPTIONS 请求无需身份验证标头即可得到处理。
builder.Services.AddCors(opts =>
opts.AddPolicy("Frontend", p =>
p.WithOrigins("https://myapp.com")
.AllowAnyHeader()
.AllowAnyMethod()));
app.UseRouting();
app.UseCors("Frontend"); // before auth — handles OPTIONS pre-flight
app.UseAuthentication();
app.UseAuthorization();常见的内置中间件
ASP.NET Core 提供许多内置中间件组件。了解每个组件的作用,有助于您理解何时以及如何使用它们。
// Compression: compresses responses (must be before static files)
builder.Services.AddResponseCompression();
app.UseResponseCompression();
// Request localization: sets culture from Accept-Language header
builder.Services.AddLocalization();
app.UseRequestLocalization();
// Health checks: /health endpoint
builder.Services.AddHealthChecks();
app.MapHealthChecks("/health");
// Forwarded headers: trust X-Forwarded-For from reverse proxy
app.UseForwardedHeaders();深入了解路由中间件
UseRouting() 会将传入请求与路由模式进行匹配,并将匹配结果存储在 HttpContext 中。随后,UseEndpoints()(或 MapXxx())会执行匹配到的端点。
app.UseRouting(); // matches route, stores in context
// Between UseRouting and Map*: middleware can read route data
app.Use(async (ctx, next) =>
{
var endpoint = ctx.GetEndpoint();
var routeName = endpoint?.DisplayName;
Console.WriteLine($"Matched: {routeName}");
await next(ctx);
});
// All auth and other middleware go here
app.UseAuthentication();
app.UseAuthorization();
// Execute the matched endpoint
app.MapControllers();
app.MapGet("/", () => "Home");响应压缩的位置
响应压缩必须放在静态文件和路由之前,这样就能在生成内容之前写入压缩后的输出。请将其紧跟在异常处理之后。
// Correct placement for response compression:
app.UseExceptionHandler();
app.UseResponseCompression(); // before static files
app.UseStaticFiles(); // compressed static files
app.UseRouting();
// ... rest of pipeline实际案例:完整的生产环境管道
将所有建议组合成一个顺序合理且安全的完整生产环境中间件堆栈。
var app = builder.Build();
if (app.Environment.IsDevelopment())
app.UseDeveloperExceptionPage();
else { app.UseExceptionHandler(); app.UseHsts(); }
app.UseResponseCompression();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors("AllowFrontend");
app.UseAuthentication();
app.UseAuthorization();
app.UseRateLimiter();
app.UseOutputCache();
app.MapHealthChecks("/health").AllowAnonymous();
app.MapControllers();
app.Run();快速检查
为什么在中间件管道中必须让 UseAuthentication 位于 UseAuthorization 之前?
回顾:中间件顺序与内置中间件
关键要点:
- 先进行异常处理,路由之前提供静态文件,身份验证先于授权,CORS 先于身份验证
- 响应压缩应尽早执行(在静态文件之前),以发挥最大效果
- UseRouting + UseAuthorization + Map* — 两者之间的中间件可以读取路由数据
- 内置中间件:UseHsts、UseHttpsRedirection、UseStaticFiles、UseRateLimiter、UseOutputCache
- 在 UseRouting 和 MapXxx 之间检查
ctx.GetEndpoint(),即可读取匹配到的路由信息
常见问题解答
「中间件顺序与内置中间件」课时是免费的吗?
是的 — 「中间件顺序与内置中间件」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 C# Academy 课程的其余内容,请升级到 CoddyKit PRO。 C# Academy 课程共包含 4 节课。
「中间件顺序与内置中间件」这节课中我会学到什么?
了解身份验证、路由、CORS 和异常处理的正确中间件顺序。 你通过在浏览器中直接运行的动手代码来练习 C# Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 C# Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 C# Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「中间件顺序与内置中间件」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 C# Academy 课中编写并运行代码吗?
能。每节 C# Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- ASP.NET Core 管道概览
- 编写自定义中间件
- 短路与分支
- 中间件顺序与内置中间件