我有一个简单的由http触发的azure函数:
[OpenApiOperation(operationId: "GetX", tags: new[] { nameof(GetXHttpTrigger) })]
[OpenApiParameter(name: "id", In = ParameterLocation.Path, Required = true, Type = typeof(Guid), Description = "X id.")]
[OpenApiResponseWithBody(statusCode: HttpStatusCode.OK, contentType: "application/json", bodyType: typeof(X), Description = "The OK response")]
[OpenApiResponseWithBody(statusCode: HttpStatusCode.NotFound, contentType: "application/json", bodyType: typeof(StatusMessage), Description = "The NotFound response")]
[Function(nameof(GetXHttpTrigger))]
public async Task<HttpResponseData> Run(
[HttpTrigger(
AuthorizationLevel.Function,
"get",
Route = "Xs/{id}")]
HttpRequestData req,
Guid id,
CancellationToken cancellationToken)
字符串
其中X是:
public class X
{
[System.Text.Json.Serialization.JsonPropertyName("combined_value")]
public string CombinedValue { get; set; }
..
型
将数据返回给调用者的代码如下所示:
var response = req.CreateResponse(HttpStatusCode.OK);
await response.WriteAsJsonAsync<X>(xData); // WriteAsJson is extension from Microsoft.Azure.Functions.Worker.Http
型
返回给调用者的数据是正确的:
{
"combined_value" : "1"
}
型
但是openId yaml生成的模式(来自http://localhost:port/api/openapi/{version}.{extension}
)忽略了属性中配置的值,只生成:
x:
type: object
properties:
combinedValue:
type: string
型
注意combinedValue是c#代码中的“lowerCased”值。有什么想法为什么会发生这种情况以及如何强制swagger考虑System.Text.Json.Serialization.JsonPropertyName属性吗?
我的主机配置非常简单:
var host = Host.CreateDefaultBuilder()
.ConfigureFunctionsWorkerDefaults((context, builder) =>
{
// do nothing
})
.ConfigureOpenApi()
型
这是我的软件包
<PackageReference Include="Microsoft.ApplicationInsights.WorkerService" Version="2.21.0" />
<PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.19.0" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.ApplicationInsights" Version="1.0.0" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http" Version="3.0.13" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.15.1" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.OpenApi" Version="1.5.1" />
型
再加上一些项目配置:
<TargetFramework>net6.0</TargetFramework>
<AzureFunctionsVersion>v4</AzureFunctionsVersion>
型
UPDATE:如果我为c# class配置Newtonsoft.Json.JsonPropertyAttribute
:
[Newtonsoft.Json.JsonProperty("combined_value")]
public string CombinedValue { get; set; }
型
生成的输出将是正确的:
x:
type: object
properties:
combined_value:
type: string
型
但是我不想混合这两种方法,在这种情况下如何使用System.Text.Json.Serialization
强制swagger?
1条答案
按热度按时间uidvcgyl1#
Microsoft.Azure.Functions.Worker.Extensions.OpenApi
nuget依赖于Newtonsoft.Json
,根据文档,它不支持System.Text.Json
。你可以完全切换到使用Newtonsoft.Json
,据我所知,它可以通过以下方式完成(没有尝试过):字符串
然后
Newtonsoft.Json.JsonProperty
将用于序列化和OpenAPI生成。或者,您可以使用这两种类型的属性:
型
或者添加自定义合约解析器,以便它将一个库的属性用于另一个库(如
System.Text.Json
->Json.NET
的here,可能需要配置JsonConvert.DefaultSettings
,反之亦然)。请参见
System.Text.Json
Support issue @github。