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<ApiBehaviorOptions>(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<IExceptionHandlerFeature>()?.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
};
以上就是ASP.NET Core 中的问题详细信息服务如何用法?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号