首页 > 解决方案 > 使用 Swashbuckle 5.x 在通用 T 参数引用属性上指定 nullable = true

问题描述

我最近使用带有 newtonsoft json nuget 的 Swashbuckle 5 将我的 API 升级到了 .net core 3.1 服务器,它产生了一个 openapi 3 模式。然后我使用 NSwag 生成 C# API。以前我有一个带有 swashbuckle 4 的 .net core 2.2 服务器,产生了一个 swagger 2.0 api 模式。

我有一个用于所有响应的通用响应类,其中包含一些有关响应的元数据,例如状态代码和消息,以及包含响应内容的通用类型 T 的 Payload 属性。

当响应是错误代码时,我将有效负载属性设置为 null。我正在努力寻找一种方法来定义我的 api,以便 swashbuckle 和 NSwag 组合生成一个 C# api,该 api 将允许有效负载属性在反序列化时为空。(swagger 2.0 / swashbuckle 4 没有问题)。

尽我所能,Payload 属性总是获取注解[Newtonsoft.Json.JsonProperty("payload", Required = Newtonsoft.Json.Required.DisallowNull...][System.ComponentModel.DataAnnotations.Required]注解。

据我了解,开放 API 3 现在允许 "$ref" 属性在模式定义中具有 "nullable": true 属性。如果我在创建后手动将其添加到我的定义中,NSwag 会正确删除 CSharp api 中的 Required 属性,并将 JsonProperty 必需属性设置为“默认”(非必需)而不是“DisallowNull”。
但是,我标记有效负载属性的任何内容都不会导致 nullable: true 出现在我的模式 json 定义中。

我想要的是这样的:

"properties": {
          "payload": {
            "nullable": true, 
            "$ref": "#/components/schemas/VisualService.Client.Models.MyResultClass"
          },

我得到的是:

"properties": {
          "payload": {
            "$ref": "#/components/schemas/VisualService.Client.Models.MyResultClass"
          },

还可以在引用的 $ref 对象本身的定义上设置“nullable”=true。我也找不到这样做的方法。

我尝试了以下补救措施,但没有成功。

  1. 使用 JsonProperty 以不同方式标记 dto 类中的属性:

    [JsonProperty(Required = Required.AllowNull)]
    public T Payload { get; set; }
    
    [AllowNull]
    public T Payload { get; set; }
    
    [MaybeNull]
    public T Payload { get; set; }
    
  2. 试图告诉 Swashbuckle / Newtonsoft 使用我在这个 github 问题中描述的自定义 Json Resolver - 似乎不服从

    services.AddControllers()
                        .AddNewtonsoftJson(options =>
                        {                        options.SerializerSettings.ContractResolver = MyCustomResolver();

  1. 我创建了自己的自定义属性和过滤器以尝试将属性设置为可为空

    [NullableGenericProperty]
    public T Payload { get; set; }
    
   [AttributeUsage(AttributeTargets.Property)]
    public class NullableGenericPropertyAttribute : Attribute
    {

    }

    public class SwaggerNullablePayloadFilter : ISchemaFilter
    {
        public void Apply(OpenApiSchema schema, SchemaFilterContext context)
        {
            if (schema?.Properties == null || context?.Type == null)
                return;

            var nullableGenericProperties = context.Type.GetProperties()
                .Where(t =>
                    t.GetCustomAttribute<NullableGenericPropertyAttribute>()
                    != null);

            foreach (var excludedProperty in nullableGenericProperties)
            {
                if (schema.Properties.ContainsKey(excludedProperty.Name.ToLowerInvariant()))
                {
                    var prop = schema.Properties[excludedProperty.Name.ToLowerInvariant()];

                    prop.Nullable = true;
                    prop.Required = new HashSet<string>() { "false" };
                }
            }
        }
    }

我在这方面取得了小小的成功,因为添加了 prop.Nullable = true; [System.ComponentModel.DataAnnotations.Required]导致从 c# api 中删除该属性。然而,它[Newtonsoft.Json.JsonProperty("payload", Required = Newtonsoft.Json.Required.DisallowNull...]仍然存在,所以它并没有太大帮助。我添加prop.Required = new HashSet<string>() { "false" };了一个额外的尝试,但它似乎没有做任何事情。

我可以再次降级到 .net core 2.2 / swashbuckle 4,但是 2.2 已经失去了长期支持,如果可能的话,我想保持在 3.1。我也可以每次都在我生成的 API 客户端上进行查找和替换,但我不想每次重新生成 api 时都手动记住要这样做,这在开发周期中每天可能会发生几次。

我有一个 hacky 解决方法 - 这是我拦截 json 响应并"nullable" = true在我的服务器上添加它需要的地方,方法是在响应正文 json 字符串上使用正则表达式匹配,然后再将其提供给客户端。虽然它真的很hacky,如果它存在,我想要一种本地方式来做到这一点。

任何和所有的帮助表示赞赏!

标签: c#swaggeropenapiswashbucklenswagstudio

解决方案


有一个设置可以做到这一点:

UseAllOfToExtendReferenceSchemas 

它将架构更改为此,nswag 可以使用它来允许 $ref 属性为空。

  "payload": {
    "required": [
      "false"
    ],
    "allOf": [
      {
        "$ref": "#/components/schemas/MyResultClass"
      }
    ],
    "nullable": true
  },

像这样使用它:

        _ = services.AddSwaggerGen(setup =>
        {
            setup.SwaggerDoc("v1", new OpenApiInfo { Title = AppConst.SwaggerTitle, Version = "v1" });

            setup.UseAllOfToExtendReferenceSchemas();
            ...

推荐阅读