如何对未处理的异常使用 "problem detail" 响应?
How to use "problem detail" responses for unhandled exceptions?
由于documented,ProblemDetails
(基于RFC 7807 规范)是ASP.NET Core 2.2 中客户端错误代码的标准响应。当我在我的 API 控制器操作方法中 return 之类的 NotFound()
时,这工作正常。
但是我如何配置我的 Web API 项目以也使用 ProblemDetails
处理未处理的异常(“500 内部服务器错误”响应)?默认情况下,此类未处理的异常要么 return 一个 HTML 主体(当调用 UseDeveloperExceptionPage()
或 UseExceptionHandler(somePath)
时),要么没有主体(如果两个方法都没有被调用)。
当 API 控制器中发生异常时,我的首选解决方案总是 return ProblemDetails
对象,但仍然 return HTML 异常页面其他(查看相关)控制器。在开发模式下,ProblemDetails
对象应该有完整的异常细节,在生产模式下只有非常有限的细节。这可能吗?
似乎 ProblemDetails
不支持 404
和 500
exception.A 解决方法是安装 Hellang.Middleware.ProblemDetails
包`,
Install-Package Hellang.Middleware.ProblemDetails
然后在startup.cs中配置,仅在开发环境下将IncludeExceptionDetails
设置为true
。
public class Startup
{
public Startup(IConfiguration configuration, IHostingEnvironment env)
{
Configuration = configuration;
CurrentEnvironment = env;
}
public IConfiguration Configuration { get; }
public IHostingEnvironment CurrentEnvironment { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddProblemDetails(setup=> {
setup.IncludeExceptionDetails = _ => CurrentEnvironment.IsDevelopment();
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
public void Configure(IApplicationBuilder app)
{
app.UseProblemDetails();
//...
}
}
参考here.
由于documented,ProblemDetails
(基于RFC 7807 规范)是ASP.NET Core 2.2 中客户端错误代码的标准响应。当我在我的 API 控制器操作方法中 return 之类的 NotFound()
时,这工作正常。
但是我如何配置我的 Web API 项目以也使用 ProblemDetails
处理未处理的异常(“500 内部服务器错误”响应)?默认情况下,此类未处理的异常要么 return 一个 HTML 主体(当调用 UseDeveloperExceptionPage()
或 UseExceptionHandler(somePath)
时),要么没有主体(如果两个方法都没有被调用)。
当 API 控制器中发生异常时,我的首选解决方案总是 return ProblemDetails
对象,但仍然 return HTML 异常页面其他(查看相关)控制器。在开发模式下,ProblemDetails
对象应该有完整的异常细节,在生产模式下只有非常有限的细节。这可能吗?
似乎 ProblemDetails
不支持 404
和 500
exception.A 解决方法是安装 Hellang.Middleware.ProblemDetails
包`,
Install-Package Hellang.Middleware.ProblemDetails
然后在startup.cs中配置,仅在开发环境下将IncludeExceptionDetails
设置为true
。
public class Startup
{
public Startup(IConfiguration configuration, IHostingEnvironment env)
{
Configuration = configuration;
CurrentEnvironment = env;
}
public IConfiguration Configuration { get; }
public IHostingEnvironment CurrentEnvironment { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddProblemDetails(setup=> {
setup.IncludeExceptionDetails = _ => CurrentEnvironment.IsDevelopment();
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
public void Configure(IApplicationBuilder app)
{
app.UseProblemDetails();
//...
}
}
参考here.