You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 6切换System.Text.Json后Swagger健康检查端点暴露异常详情

解决System.Text.Json切换后Swagger健康检查暴露Exception属性的问题

问题根源

Newtonsoft.Json默认不会序列化Exception类型的内部属性,而System.Text.Json的默认行为会序列化其所有公共属性(如Message、StackTrace、InnerException等)。切换后Swashbuckle依赖System.Text.Json生成Schema,因此会在Swagger UI中暴露这些属性。

解决方案

方案1:全局配置System.Text.Json忽略Exception属性(影响所有序列化场景)

在Program.cs中配置控制器的Json选项,让System.Text.Json序列化时跳过Exception及其子类的所有属性:

builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.TypeInfoResolverChain.Insert(0, new DefaultJsonTypeInfoResolver
        {
            Modifiers = 
            {
                typeInfo =>
                {
                    if (typeInfo.Type == typeof(Exception) || typeInfo.Type.IsSubclassOf(typeof(Exception)))
                    {
                        // 清空所有属性,避免序列化
                        typeInfo.Properties.Clear();
                    }
                }
            }
        });
    });

该配置会同时影响Swagger Schema生成和健康检查端点的实际响应内容。

方案2:仅配置Swashbuckle隐藏Exception的Schema属性(不影响实际响应)

如果只需要在Swagger UI中隐藏Exception的属性,不改变实际接口的序列化行为,可以添加自定义Swagger Schema过滤器:

  1. 注册过滤器:
builder.Services.AddSwaggerGen(options =>
{
    options.SchemaFilter<HideExceptionPropertiesFilter>();
});
  1. 实现过滤器类:
public class HideExceptionPropertiesFilter : ISchemaFilter
{
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        // 匹配Exception及其子类
        if (context.Type == typeof(Exception) || context.Type.IsSubclassOf(typeof(Exception)))
        {
            // 清空Schema中的所有属性,隐藏详情
            schema.Properties.Clear();
            // 可选:保留一个简单标识属性,比如仅保留Message
            // schema.Properties.Add("Message", new OpenApiSchema { Type = "string" });
        }
    }
}

额外说明

如果健康检查的响应格式是自定义的,也可以通过配置HealthCheckOptions来控制Exception的输出,但上述两种方案已经覆盖大部分场景。

内容的提问来源于stack exchange,提问作者Joris Mathijssen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 10:42:15