You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core 8 Web API中处理程序异常映射到IActionResult的标准方法

ASP.NET Core 8 内置异常到IActionResult的映射方案

你提到的需求,ASP.NET Core 8确实有内置的常见异常类型到HTTP状态码的映射约定,但默认未自动启用,只需通过简单配置UseExceptionHandler中间件就能激活,无需自定义复杂逻辑。

核心内置映射关系

框架原生定义了以下异常与HTTP状态码的对应规则(非完整列表):

  • BadHttpRequestException → 400 Bad Request
  • NotFoundException → 404 Not Found
  • UnauthorizedAccessException → 401 Unauthorized
  • ForbiddenAccessException → 403 Forbidden

默认状态下,所有未处理异常都会返回500状态码,要让框架自动将上述异常映射为对应状态码,只需配置异常处理中间件即可。

配置实现步骤

在Program.cs中添加UseExceptionHandler中间件,利用框架内置的映射关系返回标准的ProblemDetails响应:

var builder = WebApplication.CreateBuilder(args);

// 注册必要服务(包括MediatR、ProblemDetailsFactory等)
builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblyContaining<Program>());
builder.Services.AddControllers();

var app = builder.Build();

// 配置异常处理中间件
app.UseExceptionHandler(options =>
{
    options.Run(async context =>
    {
        var exceptionFeature = context.Features.Get<IExceptionHandlerFeature>();
        if (exceptionFeature?.Error == null) return;

        var problemDetailsFactory = context.RequestServices.GetRequiredService<ProblemDetailsFactory>();
        var statusCode = exceptionFeature.Error switch
        {
            BadHttpRequestException => StatusCodes.Status400BadRequest,
            NotFoundException => StatusCodes.Status404NotFound,
            UnauthorizedAccessException => StatusCodes.Status401Unauthorized,
            ForbiddenAccessException => StatusCodes.Status403Forbidden,
            _ => StatusCodes.Status500InternalServerError
        };

        var problemDetails = problemDetailsFactory.CreateProblemDetails(
            context,
            statusCode: statusCode,
            title: exceptionFeature.Error.Message);

        context.Response.StatusCode = statusCode;
        context.Response.ContentType = "application/problem+json";
        await context.Response.WriteAsJsonAsync(problemDetails);
    });
});

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

app.Run();

关键说明

  1. 该配置完全基于框架内置的异常类型和状态码约定,无需自定义异常或额外扩展。
  2. MediatR处理程序抛出的异常会自动冒泡到中间件被捕获,控制器无需额外处理异常逻辑。
  3. 返回的ProblemDetails符合RFC 7807标准,是API错误响应的规范格式。

内容的提问来源于stack exchange,提问作者Green Grasso Holm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 21:33:23