You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 8 Azure Functions中如何通过Microsoft OpenApi扩展实现x-enum-varnames

解决方案

在.NET 8的Azure Functions Isolated模式下,使用Microsoft.Azure.Functions.Worker.Extensions.OpenApi实现枚举名称扩展的方法如下:

1. 实现自定义Schema过滤器

创建继承自IOpenApiSchemaFilter的过滤器类,逻辑与原Swashbuckle实现一致,仅适配新的接口规范:

using Microsoft.Azure.Functions.Worker.Extensions.OpenApi.Abstractions;
using Microsoft.OpenApi.Models;
using System;
using System.Linq;

public class EnumSchemaFilter : IOpenApiSchemaFilter
{
    public void Apply(OpenApiSchema schema, OpenApiSchemaFilterContext context)
    {
        if (context.Type.IsEnum)
        {
            var enumNames = new OpenApiArray();
            enumNames.AddRange(Enum.GetNames(context.Type).Select(name => new OpenApiString(name)));
            
            // 适配NSwag的x-enumNames扩展
            schema.Extensions.Add("x-enumNames", enumNames);
            // 适配openapi-generator的x-enum-varnames扩展
            schema.Extensions.Add("x-enum-varnames", enumNames);
        }
    }
}

2. 注册过滤器到依赖注入容器

在Program.cs中,通过配置OpenApiOptions将自定义过滤器注册到服务中:

using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Extensions.OpenApi;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var host = new HostBuilder()
    .ConfigureFunctionsWebApplication()
    .ConfigureServices(services =>
    {
        services.AddApplicationInsightsTelemetryWorkerService();
        services.ConfigureFunctionsApplicationInsights();
        
        // 注册自定义枚举Schema过滤器
        services.Configure<OpenApiOptions>(options =>
        {
            options.SchemaFilters.Add<EnumSchemaFilter>();
        });
    })
    .Build();

host.Run();

3. 验证效果

启动Azure Functions后,访问默认Swagger UI路径(http://localhost:<端口号>/swagger),查看枚举类型的Schema定义,会发现已添加x-enumNames和x-enum-varnames扩展字段,openapi-generator或NSwag即可基于这些字段生成包含枚举名称的TypeScript代码。

内容的提问来源于stack exchange,提问作者Paul Johnson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 08:47:37