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

时间:2019-07-31 08:57:12

标签: c# nswag

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

"ExampleTO" : {
  "codeValidFrom" : {
    "type" : "string",
    "format" : "date"
  }
}

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; }

问题:“ codeValidFrom”中存在空值。我认为规范应如下所示:

"ExampleTO" : {
  "codeValidFrom" : {
    "type" : "string",
    "format" : "date",
    "nullable: "true"
  }
}

供应商不想进行此添加,声称该模式已生成并且无法轻易更改。

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

1 个答案:

答案 0 :(得分:0)

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

switch (context.Node)
        {
            case JoinIntoClauseSyntax joinIntoClause:
                if (IsNotValid(joinIntoClause.Identifier.Text))
                    context.ReportDiagnostic(Diagnostic.Create(Rule, joinIntoClause.Identifier.GetLocation(), joinIntoClause.Identifier.Text));
                break;
            case QueryContinuationSyntax continuationSyntax:
                if (IsNotValid(continuationSyntax.Identifier.Text))
                    context.ReportDiagnostic(Diagnostic.Create(Rule, continuationSyntax.Identifier.GetLocation(), continuationSyntax.Identifier.Text));
                break;
        }

像这样使用它(从我的代码中不太完全,未经测试):

class RequiredVisitor : JsonSchemaVisitorBase
{
    protected override Task<JsonSchema4> VisitSchemaAsync(JsonSchema4 schema, string path, string typeNameHint)
    {
        schema.RequiredProperties.Clear();
        return Task.FromResult(schema);
    }
}
相关问题