我有一个新的 .NET6 Azure Functions 应用程序。我创建了一些符合 OpenAPI 规范的 HTTP 函数。
我的 swagger 页面工作正常,除了 POST 功能。
我想在此页面上显示一个最小的正文请求作为示例。
我已经实现了 IOpenApiExample
,如 https://github.com/Azure/azure-functions-openapi-extension/blob/main/docs/openapi-core.md#openapirequestbodyattribute 中所述
但没有使用这个例子。它一直显示整个模型,没有任何样本值。
这是我的相关代码:
[FunctionName("PostHistoryEvent")]
[OpenApiOperation(operationId: "PostHistoryEvent", tags: new[] { "Post HistoryEvent" })]
[OpenApiSecurity("function_key", SecuritySchemeType.ApiKey, Name = "code", In = OpenApiSecurityLocationType.Query)]
[OpenApiRequestBody("application/json", typeof(HistoryEvent), Required = true, Description = "Description of OpenApiRequestBody", Example = typeof(HistoryEventOpenApiExample))]
[OpenApiResponseWithBody(statusCode: HttpStatusCode.Created, contentType: "application/json", bodyType: typeof(HistoryEvent), Description = "The created History Event")]
public async Task<IActionResult> PostHistoryEvent(...){...}
public class HistoryEventOpenApiExample : OpenApiExample<HistoryEvent>
{
public override IOpenApiExample<HistoryEvent> Build(NamingStrategy namingStrategy = null)
{
Examples.Add(OpenApiExampleResolver.Resolve(
"first",
new HistoryEvent()
{
ObjectId = "foo",
More properties ...
},
namingStrategy));
return this;
}
}
我想我需要添加一些东西,但我不确定是什么。
最佳答案
您在 Swagger UI 中看不到示例的原因可能是您的 Azure 函数使用的是 OpenAPI 2.0 规范(也称为 Swagger 2.0)。设置 OpenApiRequestBodyAttribute.Example
只会影响 OpenAPI 3。出于某种原因,默认情况下,Azure Functions OpenAPI 扩展库 is using OpenAPI 2.0 .
有两种方法可以解决这个问题。
选项 1。使用 OpenApiConfigurationOptions
切换到 OpenAPI 3
如果您已经有一个 OpenApiConfigurationOptions
实现类,则将 OpenApiVersion
值更新为 OpenApiVersionType.V3
。否则,just create one .
它应该看起来像这样:
public class OpenApiConfigurationOptions : DefaultOpenApiConfigurationOptions
{
public override OpenApiVersionType OpenApiVersion { get; set; } = OpenApiVersionType.V3;
// you can also update your API info as well here
// public override OpenApiInfo Info { get; set; } = new OpenApiInfo { ... };
}
选项 2。(如果您想继续使用 OpenAPI 2.0)在模型上使用 OpenApiExample
属性
将 OpenApiExample
属性添加到您的数据模型,该模型具有指向您的 HistoryEventOpenApiExample
类的链接。
[OpenApiExample(typeof(HistoryEventOpenApiExample))]
public class HistoryEvent
{
public string ObjectId { get; set; }
// More properties ...
}
引用资料
关于azure-functions - OpenApiExample 未显示在 swagger UI 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70259186/