ASP.NET Core通过RFC 7807规范实现标准化错误响应,支持自动与手动返回application/problem+json格式的结构化错误信息。在Program.cs中配置ApiBehaviorOptions和UseExceptionHandler可启用默认错误处理机制,控制器中可直接使用Problem()、ValidationProblem()或自定义ProblemDetails派生类返回详细错误,便于客户端解析与统一处理。

在 ASP.NET Core 中,问题详细信息(Problem Details)服务用于标准化错误响应格式,遵循 RFC 7807 规范。它让 API 返回结构化的错误信息,便于客户端解析和处理。
启用问题详细信息服务
ASP.NET Core 默认支持问题详细信息,尤其是在开发环境中。当你抛出异常或返回特定状态码时,框架可自动返回 application/problem+json 格式的响应。
要确保启用该功能,在 Program.cs 中配置:
var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); // 启用问题详细信息作为默认错误响应 builder.Services.Configure(options => { options.InvalidModelStateResponseFactory = context => { var problemDetails = new ValidationProblemDetails(context.ModelState) { Type = "https://tools.ietf.org/html/rfc7231#section-6.5.1", Title = "One or more validation errors occurred.", Status = StatusCodes.Status400BadRequest, Detail = "请检查请求数据是否符合要求。", Instance = context.HttpContext.Request.Path }; return new BadRequestObjectResult(problemDetails); }; }); var app = builder.Build(); app.UseExceptionHandler(exceptionHandlerApp => { exceptionHandlerApp.Run(async context => { context.Response.StatusCode = StatusCodes.Status500InternalServerError; context.Response.ContentType = "application/problem+json"; var problemDetails = new ProblemDetails { Status = StatusCodes.Status500InternalServerError, Title = "An unexpected error occurred.", Type = "https://tools.ietf.org/html/rfc7231#section-6.6.1", Detail = "请联系系统管理员或稍后重试。" }; #if DEBUG problemDetails.Extensions["traceId"] = context.TraceIdentifier; problemDetails.Extensions["message"] = context.Features.Get ()?.Error.Message; #endif await context.Response.WriteAsJsonAsync(problemDetails); }); }); app.UseHttpsRedirection(); app.MapControllers(); app.Run();
手动返回问题详细信息
你可以在控制器中直接使用 Problem()、ValidationProblem() 或构造 ProblemDetails 对象返回标准错误响应。
[HttpGet("error")]
public IActionResult TriggerError()
{
return Problem(
detail: "数据库连接失败。",
title: "服务暂时不可用",
statusCode: StatusCodes.Status503ServiceUnavailable,
type: "https://example.com/errors/db-connection-failed",
instance: Request.Path);
}
验证失败时返回问题详情
[HttpPost]
public IActionResult Create([FromBody] MyModel model)
{
if (!ModelState.IsValid)
{
return ValidationProblem();
}
// 处理逻辑
return Ok();
}
自定义问题详情类型
你可以继承 ProblemDetails 添加额外字段,比如错误代码或建议操作。
public class CustomProblemDetails : ProblemDetails
{
public string ErrorCode { get; set; }
public string[] Suggestions { get; set; }
}
使用方式:
return new ObjectResult(new CustomProblemDetails
{
Status = 400,
Title = "输入参数错误",
Detail = "邮箱格式不正确",
ErrorCode = "INVALID_EMAIL",
Suggestions = new[] { "检查邮箱拼写", "使用有效域名" },
Instance = Request.Path
})
{
StatusCode = 400
};
基本上就这些。通过合理使用问题详细信息,你的 API 错误会更清晰、统一,也更容易被前端或第三方系统处理。










