Pau*_*ems 6 swagger-ui azure-functions openapi
我有一个新的 .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;
}
}
Run Code Online (Sandbox Code Playgroud)
我想我需要添加一些东西,但我不确定什么。
您在 Swagger UI 中看不到示例的原因可能是您的 Azure 函数正在使用 OpenAPI 2.0 规范(也称为 Swagger 2.0)。设置OpenApiRequestBodyAttribute.Example只会影响 OpenAPI 3。由于某种原因,默认情况下,Azure Functions OpenAPI 扩展库使用 OpenAPI 2.0。
有两种方法可以解决这个问题。
OpenApiConfigurationOptions如果您已经有一个OpenApiConfigurationOptions实现类,则将OpenApiVersion值更新为OpenApiVersionType.V3. 否则,只需创建一个.
它应该看起来像这样:
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 { ... };
}
Run Code Online (Sandbox Code Playgroud)
OpenApiExample在模型上使用属性将OpenApiExample属性添加到具有指向您的HistoryEventOpenApiExample类的链接的数据模型。
[OpenApiExample(typeof(HistoryEventOpenApiExample))]
public class HistoryEvent
{
public string ObjectId { get; set; }
// More properties ...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3913 次 |
| 最近记录: |