1.21 中间件:掌控请求处理过程的关键.pdf

    1. Map vs MapWhen
    2. Use 与 Run 的区别
    1. if (env.IsDevelopment())
    2. {
    3. app.UseDeveloperExceptionPage();
    4. }
    5. app.Use(async (context, next) =>
    6. {
    7. //await context.Response.WriteAsync("Hello");
    8. await next();
    9. // 判断是否已经开始向响应的 body 输出内容
    10. if (context.Response.HasStarted)
    11. {
    12. // 一旦已经开始输出,则不能再修改响应头的内容
    13. }
    14. await context.Response.WriteAsync("Hello2");
    15. });
    16. // 对特定路径指定中间件
    17. app.Map("/abc", abcBuilder =>
    18. {
    19. abcBuilder.Use(async (context, next) =>
    20. {
    21. //await context.Response.WriteAsync("Hello");
    22. await next();
    23. await context.Response.WriteAsync("Hello2");
    24. });
    25. });
    26. // 对特定条件指定中间件
    27. app.MapWhen(context =>
    28. {
    29. return context.Request.Query.Keys.Contains("abc");
    30. }, builder =>
    31. {
    32. // 与 Use 不同。
    33. // Use 里面可以接 next 继续执行后续中间件
    34. // Run 表示中间件执行的末端,不再执行后面的中间件
    35. builder.Run(async context =>
    36. {
    37. await context.Response.WriteAsync("new abc");
    38. });
    39. });
    40. app.UseMyMiddleware();
    41. app.UseHttpsRedirection();
    42. app.UseRouting();
    43. app.UseAuthorization();
    44. app.UseEndpoints(endpoints =>
    45. {
    46. endpoints.MapControllers();
    47. });