-
Notifications
You must be signed in to change notification settings - Fork 22
ASP .NET Core添加Problem Details
L edited this page Mar 5, 2023
·
3 revisions
引用
Hellang.Middleware.ProblemDetails
注册服务
//add ProblemDetails
//为异常消息统一规范格式
//统一处理异常,为不同的异常设置不同的信息
builder.Services.AddProblemDetails(opts =>
{
opts.IncludeExceptionDetails = (ctx, ex) =>
{
return false;
};
opts.Map<CustomException>((ex) =>
{
var pd = StatusCodeProblemDetails.Create(StatusCodes.Status403Forbidden);
pd.Detail = ex.Message;
return pd;
});
opts.Map<Exception>((ex) =>
{
var pd = StatusCodeProblemDetails.Create(StatusCodes.Status500InternalServerError);
pd.Detail = ex.Message;
return pd;
});
});
设置测试Api
[ApiController]
[Route("[controller]")]
public class ExceptionTestController : ControllerBase
{
[HttpGet(nameof(Return404))]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
public IActionResult Return404()
{
return new NotFoundResult();
}
}
如果需要添加额外信息,可以使用Extensions
字典
opts.Map<Exception>((ex) =>
{
var pd = StatusCodeProblemDetails.Create(StatusCodes.Status500InternalServerError);
pd.Detail = ex.Message;
pd.Extensions.Add("key1", "value1");
pd.Extensions.Add("key2", 2);
return pd;
});
Program.cs
ExceptionTestController.cs
Problem Details for HTTP APIs
ProblemDetails.cs
ProblemDetails 类
Hellang.Middleware.ProblemDetails