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

Azure Function无法生成OpenApi文档问题排查求助

问题:Azure Functions OpenAPI 扩展不生成端点及404异常

我定义了如下RegistrationFunction函数:

public class RegistrationFunction(
    IUserExistsQuery userExistsQuery,
    IRegisterUserCommand registerUser)
{
    [Function(nameof(RegistrationFunction))]
    [OpenApiOperation(operationId: "RegisterUser", Visibility = OpenApiVisibilityType.Important)]
    [OpenApiSecurity("function_key", SecuritySchemeType.ApiKey, Name = "x-functions-key", In = OpenApiSecurityLocationType.Header)]
    [OpenApiRequestBody(contentType: MediaTypeNames.Application.Json, bodyType: typeof(UserDataRequestBody))]
    [OpenApiResponseWithoutBody(statusCode: HttpStatusCode.OK)]
    [OpenApiResponseWithoutBody(statusCode: HttpStatusCode.Conflict)]
    [OpenApiResponseWithBody(statusCode: HttpStatusCode.BadRequest, bodyType: typeof(RegistrationErrorResponseBody), contentType: MediaTypeNames.Application.Json)]
    public async Task<HttpResponseData> Run(
        [HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequestData req,
        [FromBody] UserDataRequestBody userData)
    {
        // 代码省略
    }
}

已添加OpenAPI相关包引用:

<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.OpenApi" Version="1.5.1" />

Program.cs中的配置代码:

var host = new HostBuilder()
    .UseServiceProviderFactory(new AutofacServiceProviderFactory())
    .ConfigureContainer<ContainerBuilder>(builder =>
    {
        builder.RegisterType<UserExistsQuery>().AsImplementedInterfaces().SingleInstance();
        builder.RegisterType<RegisterUserCommand>().AsImplementedInterfaces().SingleInstance();
    })
    .ConfigureServices(services =>
    {
        services.AddDbContext<MLTRContext>(options =>
        {
            var connectionString = Environment.GetEnvironmentVariable("PostgresConnectionString");
            
            options.UseNpgsql(connectionString);
        });
        services.AddSingleton<IOpenApiConfigurationOptions>(_ =>
        {
            var options = new OpenApiConfigurationOptions
            {
                Info = new OpenApiInfo
                {
                    Version = DefaultOpenApiConfigurationOptions.GetOpenApiDocVersion(),
                    Title = $"{DefaultOpenApiConfigurationOptions.GetOpenApiDocTitle()} (Injected)",
                    Description = DefaultOpenApiConfigurationOptions.GetOpenApiDocDescription(),
                    TermsOfService = new Uri("https://github.com/Azure/azure-functions-openapi-extension"),
                    Contact = new OpenApiContact
                    {
                        Name = "Enquiry",
                        Email = "azfunc-openapi@microsoft.com",
                        Url = new Uri("https://github.com/Azure/azure-functions-openapi-extension/issues"),
                    },
                    License = new OpenApiLicense
                    {
                        Name = "MIT",
                        Url = new Uri("http://opensource.org/licenses/MIT"),
                    }
                },
                Servers = DefaultOpenApiConfigurationOptions.GetHostNames(),
                OpenApiVersion = DefaultOpenApiConfigurationOptions.GetOpenApiVersion(),
                IncludeRequestingHostName = DefaultOpenApiConfigurationOptions.IsFunctionsRuntimeEnvironmentDevelopment(),
                ForceHttps = DefaultOpenApiConfigurationOptions.IsHttpsForced(),
                ForceHttp = DefaultOpenApiConfigurationOptions.IsHttpForced(),
            };

            return options;
        });
    })
    .ConfigureFunctionsWorkerDefaults(w => 
        w
            .UseMiddleware<ErrorExposingMiddleware>()
            .UseMiddleware<PrintEnvVarsMiddleware>())
    .Build();

await host.RunAsync();

本地构建运行后,控制台未显示任何OpenAPI端点,访问/api/swagger/ui返回404。我有两个疑问:

  • 是否因为项目结构非标准?项目结构如下:
| - Program.cs
| - local.settings.json
| | - Functions
| | | - Registration
| | | | - RegistrationFunction.cs
  • 或是因为使用了<TargetFramework>net8.0</TargetFramework>,而官方示例最高仅用到net7.0?

问题原因及解决办法

1. 包引用错误(核心问题)

你的项目是隔离进程模型(Worker)的Azure Functions(从ConfigureFunctionsWorkerDefaults可判断),但你安装的Microsoft.Azure.WebJobs.Extensions.OpenApi是给进程内模型使用的包。需要替换为隔离进程专用的OpenAPI扩展包:

<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.OpenApi" Version="1.5.1" />

同时移除原有的Microsoft.Azure.WebJobs.Extensions.OpenApi包,避免版本冲突。

2. .NET 8兼容性

当前Microsoft.Azure.Functions.Worker.Extensions.OpenApi 1.5.1版本已支持.NET 8,框架版本不是问题。

3. 项目结构

你的项目结构符合规范,Functions目录下的函数类会被正常扫描加载,无需调整。

4. 额外配置检查

  • 确保local.settings.json中FUNCTIONS_WORKER_RUNTIME设置为dotnet-isolated:
{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated"
  }
}
  • 重启项目后,控制台应输出以下OpenAPI相关端点:
    • /api/swagger.json
    • /api/swagger/ui
    • /api/openapi.json

5. 中间件顺序(可选)

如果问题仍存在,检查中间件注册顺序,确保OpenApi相关中间件被正确加载(使用正确包的情况下会自动注册)。

内容的提问来源于stack exchange,提问作者Marek M.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 08:23:19