.NET Core 7中AddProblemDetails如何始终返回响应体错误详情?
解决AddProblemDetails在非开发环境不返回响应体错误详情的问题
ASP.NET Core 的 AddProblemDetails 组件默认仅在 Development 环境下将异常详情(如堆栈跟踪、错误消息)包含到响应体的 ProblemDetails 中,非开发环境会隐藏这类敏感信息,仅返回基础状态码或通过响应头传递信息。要实现所有环境都在响应体中显示完整错误详情,需修改其配置选项。
解决方案
将原代码中的 .AddProblemDetails() 替换为带自定义配置的版本,强制开启所有环境下的异常详情输出:
builder.Services.AddProblemDetails(options => { // 让所有环境都将异常详情包含到响应体的ProblemDetails中 options.IncludeExceptionDetails = (context, exception) => true; // 可选:添加自定义扩展字段,比如请求跟踪ID,方便生产环境排查问题 options.CustomizeProblemDetails = context => { context.ProblemDetails.Extensions["traceId"] = context.HttpContext.TraceIdentifier; }; });
配置说明
IncludeExceptionDetails:该委托控制是否将异常详情加入响应体,默认逻辑仅在Development环境返回true。设置为始终返回true后,所有环境都会输出完整错误信息。CustomizeProblemDetails:可选配置,用于向 ProblemDetails 添加自定义扩展内容,比如请求的 TraceID,这在生产环境定位问题时很实用。
修改后的完整Program.cs代码
var builder = WebApplication.CreateBuilder(args); builder.Host.UseSerilog((context, config) => config.ReadFrom.Configuration(context.Configuration)); builder.Services.AddCustomCors() .AddAuthSupport(builder.Configuration) .AddCustomJson() .AddHttpClient() .AddProblemDetails(options => { options.IncludeExceptionDetails = (_, __) => true; options.CustomizeProblemDetails = context => { context.ProblemDetails.Extensions["traceId"] = context.HttpContext.TraceIdentifier; }; }); builder.Services.AddDatabase(builder.Configuration) .AddCustomFluentValidation() .AddOpenAPISupport(); var app = builder.Build(); app.UseCors() .UseFullSwaggerUI() .UseHttpsRedirection() .UseAuthentication() .UseAuthorization(); app.MapEndpoints(); app.Run();
注意事项
生产环境返回完整异常详情可能存在安全风险,建议根据实际场景调整:比如仅在 staging 等非生产环境开启,或自定义返回内容,避免泄露敏感的业务/系统细节。
内容的提问来源于stack exchange,提问作者Andy Nguyen
相关产品推荐
相关产品推荐

