处理 ASP.NET Core Web API 中的错误Handle errors in ASP.NET Core web APIs

本文内容

本文介绍如何处理和自定义 ASP.NET Core Web API 的错误处理。

查看或下载示例代码如何下载

开发人员异常页Developer Exception Page

开发人员异常页是一种用于获取服务器错误详细堆栈跟踪的有用工具。它使用 DeveloperExceptionPageMiddleware 来捕获 HTTP 管道中的同步和异步异常,并生成错误响应。为了进行说明,请考虑以下控制器操作:

  1. [HttpGet("{city}")]
  2. public WeatherForecast Get(string city)
  3. {
  4. if (!string.Equals(city?.TrimEnd(), "Redmond", StringComparison.OrdinalIgnoreCase))
  5. {
  6. throw new ArgumentException(
  7. $"We don't offer a weather forecast for {city}.", nameof(city));
  8. }
  9. return GetWeather().First();
  10. }

运行以下 curl 命令以测试前面的操作:

  1. curl -i https://localhost:5001/weatherforecast/chicago

在 ASP.NET Core 3.0 及更高版本中,如果客户端不请求 HTML 格式的输出,则开发人员异常页将显示纯文本响应。将显示以下输出:

  1. HTTP/1.1 500 Internal Server Error
  2. Transfer-Encoding: chunked
  3. Content-Type: text/plain
  4. Server: Microsoft-IIS/10.0
  5. X-Powered-By: ASP.NET
  6. Date: Fri, 27 Sep 2019 16:13:16 GMT
  7. System.ArgumentException: We don't offer a weather forecast for chicago. (Parameter 'city')
  8. at WebApiSample.Controllers.WeatherForecastController.Get(String city) in C:\working_folder\aspnet\AspNetCore.Docs\aspnetcore\web-api\handle-errors\samples\3.x\Controllers\WeatherForecastController.cs:line 34
  9. at lambda_method(Closure , Object , Object[] )
  10. at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
  11. at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
  12. at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Logged|12_1(ControllerActionInvoker invoker)
  13. at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
  14. at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
  15. at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
  16. at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
  17. --- End of stack trace from previous location where exception was thrown ---
  18. at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
  19. at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
  20. at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
  21. at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
  22. at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
  23. HEADERS
  24. =======
  25. Accept: */*
  26. Host: localhost:44312
  27. User-Agent: curl/7.55.1

要改为显示 HTML 格式的响应,请将 Accept HTTP 请求头设置为 text/html 媒体类型。例如:

  1. curl -i -H "Accept: text/html" https://localhost:5001/weatherforecast/chicago

请考虑以下 HTTP 响应摘录:

在 ASP.NET Core 2.2 及更低版本中,开发人员异常页将显示 HTML 格式的响应。例如,请考虑以下 HTTP 响应摘录:

  1. HTTP/1.1 500 Internal Server Error
  2. Transfer-Encoding: chunked
  3. Content-Type: text/html; charset=utf-8
  4. Server: Microsoft-IIS/10.0
  5. X-Powered-By: ASP.NET
  6. Date: Fri, 27 Sep 2019 16:55:37 GMT
  7. <!DOCTYPE html>
  8. <html lang="en" xmlns="http://www.w3.org/1999/xhtml">
  9. <head>
  10. <meta charset="utf-8" />
  11. <title>Internal Server Error</title>
  12. <style>
  13. body {
  14. font-family: 'Segoe UI', Tahoma, Arial, Helvetica, sans-serif;
  15. font-size: .813em;
  16. color: #222;
  17. background-color: #fff;
  18. }

通过 Postman 等工具进行测试时,HTML 格式的响应会很有用。以下屏幕截图显示了 Postman 中的纯文本和 HTML 格式的响应:

Postman 中的开发人员异常页测试

警告

仅当应用程序在开发环境中运行时才启用开发人员异常页。否则当应用程序在生产环境中运行时,详细的异常信息会向公众泄露有关配置环境的详细信息,请参阅 在 ASP.NET Core 中使用多个环境

异常处理程序Exception handler

在非开发环境中,可使用异常处理中间件来生成错误负载:

  1. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  2. {
  3. if (env.IsDevelopment())
  4. {
  5. app.UseDeveloperExceptionPage();
  6. }
  7. else
  8. {
  9. app.UseExceptionHandler("/error");
  10. }
  11. app.UseHttpsRedirection();
  12. app.UseRouting();
  13. app.UseAuthorization();
  14. app.UseEndpoints(endpoints =>
  15. {
  16. endpoints.MapControllers();
  17. });
  18. }
  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  2. {
  3. if (env.IsDevelopment())
  4. {
  5. app.UseDeveloperExceptionPage();
  6. }
  7. else
  8. {
  9. app.UseExceptionHandler("/error");
  10. app.UseHsts();
  11. }
  12. app.UseHttpsRedirection();
  13. app.UseMvc();
  14. }
  • 配置控制器操作以响应 /error 路由:
  1. [ApiController]
  2. public class ErrorController : ControllerBase
  3. {
  4. [Route("/error")]
  5. public IActionResult Error() => Problem();
  6. }
  1. [ApiController]
  2. public class ErrorController : ControllerBase
  3. {
  4. [Route("/error")]
  5. public ActionResult Error([FromServices] IHostingEnvironment webHostEnvironment)
  6. {
  7. var feature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
  8. var ex = feature?.Error;
  9. var isDev = webHostEnvironment.IsDevelopment();
  10. var problemDetails = new ProblemDetails
  11. {
  12. Status = (int)HttpStatusCode.InternalServerError,
  13. Instance = feature?.Path,
  14. Title = isDev ? $"{ex.GetType().Name}: {ex.Message}" : "An error occurred.",
  15. Detail = isDev ? ex.StackTrace : null,
  16. };
  17. return StatusCode(problemDetails.Status.Value, problemDetails);
  18. }
  19. }

前面的 Error 操作向客户端发送符合 RFC 7807 的负载。

异常处理中间件还可以在本地开发环境中提供更详细的内容协商输出。使用以下步骤在开发和生产环境中生成一致的负载格式:

  • Startup.Configure 中,注册特定于环境的异常处理中间件实例:
  1. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  2. {
  3. if (env.IsDevelopment())
  4. {
  5. app.UseExceptionHandler("/error-local-development");
  6. }
  7. else
  8. {
  9. app.UseExceptionHandler("/error");
  10. }
  11. }
  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  2. {
  3. if (env.IsDevelopment())
  4. {
  5. app.UseExceptionHandler("/error-local-development");
  6. }
  7. else
  8. {
  9. app.UseExceptionHandler("/error");
  10. }
  11. }

在上述代码中,通过以下方法注册了中间件:

  • 开发环境中 /error-local-development 的路由。
  • 非开发环境中 /error 的路由。
    • 将属性路由应用于控制器操作:
  1. [ApiController]
  2. public class ErrorController : ControllerBase
  3. {
  4. [Route("/error-local-development")]
  5. public IActionResult ErrorLocalDevelopment(
  6. [FromServices] IWebHostEnvironment webHostEnvironment)
  7. {
  8. if (webHostEnvironment.EnvironmentName != "Development")
  9. {
  10. throw new InvalidOperationException(
  11. "This shouldn't be invoked in non-development environments.");
  12. }
  13. var context = HttpContext.Features.Get<IExceptionHandlerFeature>();
  14. return Problem(
  15. detail: context.Error.StackTrace,
  16. title: context.Error.Message);
  17. }
  18. [Route("/error")]
  19. public IActionResult Error() => Problem();
  20. }
  1. [ApiController]
  2. public class ErrorController : ControllerBase
  3. {
  4. [Route("/error-local-development")]
  5. public IActionResult ErrorLocalDevelopment(
  6. [FromServices] IHostingEnvironment webHostEnvironment)
  7. {
  8. if (!webHostEnvironment.IsDevelopment())
  9. {
  10. throw new InvalidOperationException(
  11. "This shouldn't be invoked in non-development environments.");
  12. }
  13. var feature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
  14. var ex = feature?.Error;
  15. var problemDetails = new ProblemDetails
  16. {
  17. Status = (int)HttpStatusCode.InternalServerError,
  18. Instance = feature?.Path,
  19. Title = ex.GetType().Name,
  20. Detail = ex.StackTrace,
  21. };
  22. return StatusCode(problemDetails.Status.Value, problemDetails);
  23. }
  24. [Route("/error")]
  25. public ActionResult Error(
  26. [FromServices] IHostingEnvironment webHostEnvironment)
  27. {
  28. var feature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
  29. var ex = feature?.Error;
  30. var isDev = webHostEnvironment.IsDevelopment();
  31. var problemDetails = new ProblemDetails
  32. {
  33. Status = (int)HttpStatusCode.InternalServerError,
  34. Instance = feature?.Path,
  35. Title = isDev ? $"{ex.GetType().Name}: {ex.Message}" : "An error occurred.",
  36. Detail = isDev ? ex.StackTrace : null,
  37. };
  38. return StatusCode(problemDetails.Status.Value, problemDetails);
  39. }
  40. }

使用异常来修改响应Use exceptions to modify the response

可以从控制器之外修改响应的内容。在 ASP.NET 4.x Web API 中,执行此操作的一种方法是使用 HttpResponseException 类型。ASP.NET Core 不包括等效类型。可以使用以下步骤来添加对 HttpResponseException 的支持:

  • 创建名为 HttpResponseException 的已知异常类型:
  1. public class HttpResponseException : Exception
  2. {
  3. public int Status { get; set; } = 500;
  4. public object Value { get; set; }
  5. }
  • 创建名为 HttpResponseExceptionFilter 的操作筛选器:
  1. public class HttpResponseExceptionFilter : IActionFilter, IOrderedFilter
  2. {
  3. public int Order { get; set; } = int.MaxValue - 10;
  4. public void OnActionExecuting(ActionExecutingContext context) { }
  5. public void OnActionExecuted(ActionExecutedContext context)
  6. {
  7. if (context.Exception is HttpResponseException exception)
  8. {
  9. context.Result = new ObjectResult(exception.Value)
  10. {
  11. StatusCode = exception.Status,
  12. };
  13. context.ExceptionHandled = true;
  14. }
  15. }
  16. }
  • Startup.ConfigureServices 中,将操作筛选器添加到筛选器集合:
  1. services.AddControllers(options =>
  2. options.Filters.Add(new HttpResponseExceptionFilter()));
  1. services.AddMvc(options =>
  2. options.Filters.Add(new HttpResponseExceptionFilter()))
  3. .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
  1. services.AddMvc(options =>
  2. options.Filters.Add(new HttpResponseExceptionFilter()))
  3. .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

验证失败错误响应Validation failure error response

对于 Web API 控制器,如果模型验证失败,MVC 将使用 ValidationProblemDetails 响应类型做出响应。MVC 使用 InvalidModelStateResponseFactory 的结果来构造验证失败的错误响应。下面的示例使用工厂在 SerializableError 中将默认响应类型更改为 Startup.ConfigureServices

  1. services.AddControllers()
  2. .ConfigureApiBehaviorOptions(options =>
  3. {
  4. options.InvalidModelStateResponseFactory = context =>
  5. {
  6. var result = new BadRequestObjectResult(context.ModelState);
  7. // TODO: add `using using System.Net.Mime;` to resolve MediaTypeNames
  8. result.ContentTypes.Add(MediaTypeNames.Application.Json);
  9. result.ContentTypes.Add(MediaTypeNames.Application.Xml);
  10. return result;
  11. };
  12. });
  1. services.AddMvc()
  2. .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
  3. .ConfigureApiBehaviorOptions(options =>
  4. {
  5. options.InvalidModelStateResponseFactory = context =>
  6. {
  7. var result = new BadRequestObjectResult(context.ModelState);
  8. // TODO: add `using using System.Net.Mime;` to resolve MediaTypeNames
  9. result.ContentTypes.Add(MediaTypeNames.Application.Json);
  10. result.ContentTypes.Add(MediaTypeNames.Application.Xml);
  11. return result;
  12. };
  13. });
  1. services.AddMvc()
  2. .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
  3. services.Configure<ApiBehaviorOptions>(options =>
  4. {
  5. options.InvalidModelStateResponseFactory = context =>
  6. {
  7. var result = new BadRequestObjectResult(context.ModelState);
  8. // TODO: add `using using System.Net.Mime;` to resolve MediaTypeNames
  9. result.ContentTypes.Add(MediaTypeNames.Application.Json);
  10. result.ContentTypes.Add(MediaTypeNames.Application.Xml);
  11. return result;
  12. };
  13. });

客户端错误响应Client error response

错误结果定义为具有 HTTP 状态代码 400 或更高的结果。对于 Web API 控制器,MVC 会将错误结果转换为具有 ProblemDetails 的结果。

重要

ASP.NET Core 2.1 生成一个基本符合 RFC 7807 的问题详细信息响应。如果需要达到百分百的符合性,请将项目升级到 ASP.NET Core 2.2 或更高版本。

可以通过以下方式之一配置错误响应:

实现 ProblemDetailsFactoryImplement ProblemDetailsFactory

MVC 使用 Microsoft.AspNetCore.Mvc.ProblemDetailsFactory 生成 ProblemDetailsValidationProblemDetails 的所有实例。这包括客户端错误响应、验证失败错误响应以及 Microsoft.AspNetCore.Mvc.ControllerBase.ProblemValidationProblem() 帮助程序方法。

若要自定义问题详细信息响应,请在 ProblemDetailsFactory 中注册 Startup.ConfigureServices 的自定义实现:

  1. public void ConfigureServices(IServiceCollection serviceCollection)
  2. {
  3. services.AddControllers();
  4. services.AddTransient<ProblemDetailsFactory, CustomProblemDetailsFactory>();
  5. }

可以按照使用 ApiBehaviorOptions.ClientErrorMapping 部分所述的方式配置错误响应。

使用 ApiBehaviorOptions.ClientErrorMappingUse ApiBehaviorOptions.ClientErrorMapping

使用 ClientErrorMapping 属性配置 ProblemDetails 响应的内容。例如,Startup.ConfigureServices 中的以下代码会更新 404 响应的 type 属性:

  1. services.AddControllers()
  2. .ConfigureApiBehaviorOptions(options =>
  3. {
  4. options.SuppressConsumesConstraintForFormFileParameters = true;
  5. options.SuppressInferBindingSourcesForParameters = true;
  6. options.SuppressModelStateInvalidFilter = true;
  7. options.SuppressMapClientErrors = true;
  8. options.ClientErrorMapping[404].Link =
  9. "https://httpstatuses.com/404";
  10. });
  1. services.AddMvc()
  2. .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
  3. .ConfigureApiBehaviorOptions(options =>
  4. {
  5. options.SuppressConsumesConstraintForFormFileParameters = true;
  6. options.SuppressInferBindingSourcesForParameters = true;
  7. options.SuppressModelStateInvalidFilter = true;
  8. options.SuppressMapClientErrors = true;
  9. options.ClientErrorMapping[404].Link =
  10. "https://httpstatuses.com/404";
  11. });