Header中DataTime/DateTimeOffset参数为空,导致NSwag生成客户端出错



我们有一个开放Api规范,我们正在使用MSBuild中的NSwag openapi2csclient来生成Http客户端。

<Target Name="NSwag" BeforeTargets="BeforeBuild">
<Exec Command="$(NSwagExe) openapi2csclient /OperationGenerationMode:MultipleClientsFromFirstTagAndPathSegments /UseBaseUrl:false /namespace:FooSpace /GenerateOptionalParameters:true /GenerateClientInterfaces:true /input:Clients/FooSpace/FooSpace-OpenApi.json /output:Clients/FooSpace/FooSpaceClient.cs" />
</Target>

然而,似乎有一个问题,当添加一个非必需的DateTime/DateTimeOffset作为一个参数到任何方法的头,因为这似乎是作为一个可空的DateTime?/DateTimeOffset?

Open Api文档中的相关参数:

{
"name": "Updated",
"in": "header",
"schema": {
"type": "string",
"format": "date-time"
}
}

生成的失败代码片段:

if (updatedHeader != null)
request_.Headers.TryAddWithoutValidation("Updated", ConvertToString(updatedHeader.ToString("s"), System.Globalization.CultureInfo.InvariantCulture));

上面的代码段抛出错误:

不重载方法'ToString'接受1个参数

具有相同参数的查询参数工作正常,因为在生成的代码中使用了Nullable的Value属性:

if (updatedQuery != null)
{
urlBuilder_.Append(System.Uri.EscapeDataString("Updated") + "=").Append(System.Uri.EscapeDataString(updatedQuery.Value.ToString("s", System.Globalization.CultureInfo.InvariantCulture))).Append("&");
}

是否有任何解决方法?

问题的根源在于NSwag源代码(链接)中的液态模板只在参数设置为Nullable时才添加空条件运算符,如下所示:{% if parameter.IsNullable %}?{% endif %}.

问题是,当定义一个可选参数时(就像我们的情况一样),NSwag默认不认为它是可空的。因此,我们通过添加一行代码来解决这个问题,显式地将值类型设置为Nullable,如下所示:

if (property.PropertyType.IsValueType == true) 
openApiParameter.Schema.Nullable = true;

最新更新