使 NSwag 生成的客户端中的属性可为空

Tvd*_*vdH 5 c# nswag

我从供应商处获得了 (OpenApi 3.0.1) 中的对象规范:

"ExampleTO" : {
  "codeValidFrom" : {
    "type" : "string",
    "format" : "date"
  }
}
Run Code Online (Sandbox Code Playgroud)

NSwag 在 C# 客户端中生成此属性(我认为正确):

[Newtonsoft.Json.JsonProperty("codeValidFrom",
 Required = Newtonsoft.Json.Required.DisallowNull,
 NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
[Newtonsoft.Json.JsonConverter(typeof(DateFormatConverter))]
public System.DateTimeOffset CodeValidFrom { get; set; }
Run Code Online (Sandbox Code Playgroud)

问题:“codeValidFrom”中有空值。我认为规范应该是这样的:

"ExampleTO" : {
  "codeValidFrom" : {
    "type" : "string",
    "format" : "date",
    "nullable: "true"
  }
}
Run Code Online (Sandbox Code Playgroud)

供应商不想进行此添加,声称架构是生成的并且不能轻易更改。

有没有办法让 NSwag 客户端仍然可以使用此功能?理想情况下,我将使所有字符串属性都可为空。

No *_*o U 1

我在第三方 API 中遇到了类似的问题,该问题在于其属性的可为空性。我使用的是我自己编写的客户端生成器,因此我给了它一个使用模式访问者的选项(在问题 #1814中讨论作为不同问题的解决方案)来清除 Swagger 文档的“必需”属性集合,从而使所有属性默认为可为空。您可能可以通过在解析 JSON 之前对其进行操作来实现相同的目的。

class RequiredVisitor : JsonSchemaVisitorBase
{
    protected override Task<JsonSchema4> VisitSchemaAsync(JsonSchema4 schema, string path, string typeNameHint)
    {
        schema.RequiredProperties.Clear();
        return Task.FromResult(schema);
    }
}
Run Code Online (Sandbox Code Playgroud)

像这样使用它(不是我的代码中的逐字记录,未经测试):

var doc = await SwaggerDocument.FromJsonAsync(json);
await new RequiredVisitor().VisitAsync(doc);
Run Code Online (Sandbox Code Playgroud)