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

如何为.NET Framework4.8独立模式Azure Function(v4)生成OpenAPI文档

问题根源分析

你遇到的'OpenApiOperation' is not an attribute class错误,核心原因是OpenAPI扩展包与Functions模型不匹配:

  • 你使用的Microsoft.Azure.Functions.Worker.Extensions.OpenApi是为.NET 6+的孤立进程模型(Functions v4)设计的,但该模型不支持.NET Framework4.8;
  • 由于必须依赖.NET Framework4.8调用SOAP服务,你只能选择Functions v1或Functions v4的进程内(In-Process)模型——这两个模型基于WebJobs SDK,而非Worker SDK,因此Worker版本的OpenApi属性完全不兼容。
解决方案(适配.NET Framework4.8)

方案一:使用Functions v4 进程内模型(推荐)

v4进程内模型支持.NET Framework4.8,且有官方OpenAPI扩展支持:

  1. 调整项目配置:确保Azure Function项目为v4进程内模型(创建时选择".NET Framework 4.8"作为目标框架,模型选"In-Process")。
  2. 替换NuGet包:卸载所有Worker相关包(Microsoft.Azure.Functions.Worker、Microsoft.Azure.Functions.Worker.Extensions.OpenApi等),安装适配WebJobs SDK的包:
    Install-Package Microsoft.Azure.WebJobs.Extensions.OpenApi -Version 1.5.1
    Install-Package Swashbuckle.AspNetCore.Swagger -Version 6.4.0
    Install-Package Swashbuckle.AspNetCore.SwaggerUi -Version 6.4.0
    
  3. 修正代码命名空间与属性:
    • 替换Worker相关命名空间为WebJobs SDK的命名空间;
    • 使用WebJobs版本的OpenApi属性,示例代码:
      using System;
      using System.Threading.Tasks;
      using Microsoft.Azure.WebJobs;
      using Microsoft.Azure.WebJobs.Extensions.Http;
      using Microsoft.AspNetCore.Http;
      using Microsoft.Extensions.Logging;
      using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Attributes;
      using Microsoft.OpenApi.Models;
      using Microsoft.AspNetCore.Mvc;
      using System.Net;
      
      namespace TGAFunction
      {
          public static class GetData
          {
              [FunctionName("GetServerTime")]
              [OpenApiOperation(operationId: "GetServerTime", tags: new[] { "TGA API" }, Summary = "Retrieve server time", Description = "This API returns the current server time")]
              [OpenApiParameter(name: "username", In = ParameterLocation.Query, Required = true, Type = typeof(string), Description = "The **username** parameter")]
              [OpenApiParameter(name: "password", In = ParameterLocation.Query, Required = true, Type = typeof(string), Description = "The **password** parameter")]
              [OpenApiResponseWithBody(statusCode: HttpStatusCode.OK, contentType: "application/json", bodyType: typeof(string), Description = "The operation completed successfully")]
              [OpenApiResponseWithBody(statusCode: HttpStatusCode.BadRequest, contentType: "application/json", bodyType: typeof(string), Description = "The operation was not completed successfully")]
              public static async Task<IActionResult> GetServerTime(
                  [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
                  ILogger log)
              {
                  // 你的业务逻辑代码
                  return new OkObjectResult(DateTime.Now.ToString());
              }
          }
      }
      
  4. 注册Swagger服务:添加Startup.cs文件(若不存在),配置OpenApi服务:
    using Microsoft.Azure.WebJobs;
    using Microsoft.Azure.WebJobs.Hosting;
    using Microsoft.Extensions.DependencyInjection;
    
    [assembly: WebJobsStartup(typeof(TGAFunction.Startup))]
    namespace TGAFunction
    {
        public class Startup : IWebJobsStartup
        {
            public void Configure(IWebJobsBuilder builder)
            {
                builder.AddOpenApi();
            }
        }
    }
    
  5. 测试访问:启动项目后,访问http://localhost:7071/api/swagger/ui即可查看生成的OpenAPI文档。

方案二:使用Functions v1模型

若必须依赖v1,需手动集成Swagger:

  1. 安装Swashbuckle包:
    Install-Package Swashbuckle.AspNetCore.Swagger -Version 5.6.3
    Install-Package Swashbuckle.AspNetCore.SwaggerGen -Version 5.6.3
    Install-Package Swashbuckle.AspNetCore.SwaggerUi -Version 5.6.3
    
  2. 添加Swagger生成函数:创建两个Http触发函数,分别生成Swagger JSON和提供UI:
    using System.IO;
    using System.Net;
    using System.Net.Http;
    using System.Threading.Tasks;
    using Microsoft.Azure.WebJobs;
    using Microsoft.Azure.WebJobs.Extensions.Http;
    using Microsoft.AspNetCore.Http;
    using Microsoft.Extensions.Logging;
    using Swashbuckle.AspNetCore.SwaggerGen;
    using Microsoft.OpenApi.Models;
    
    namespace TGAFunction
    {
        public static class SwaggerFunctions
        {
            [FunctionName("SwaggerJson")]
            public static async Task<HttpResponseMessage> SwaggerJson(
                [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "swagger/json")] HttpRequestMessage req,
                ILogger log)
            {
                var swaggerGen = new SwaggerGenerator(new SwaggerGeneratorOptions
                {
                    Info = new OpenApiInfo { Title = "TGA API", Version = "v1" }
                });
                var swaggerDoc = swaggerGen.GenerateSwagger("v1", null);
                return req.CreateResponse(HttpStatusCode.OK, swaggerDoc, "application/json");
            }
    
            [FunctionName("SwaggerUi")]
            public static HttpResponseMessage SwaggerUi(
                [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "swagger/ui")] HttpRequestMessage req,
                ILogger log)
            {
                var uiContent = File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "Swagger", "index.html"));
                var response = new HttpResponseMessage(HttpStatusCode.OK);
                response.Content = new StringContent(uiContent, System.Text.Encoding.UTF8, "text/html");
                return response;
            }
        }
    }
    
  3. 添加Swagger UI静态文件:在项目中创建Swagger文件夹,放入Swagger UI的index.html文件,设置文件属性为"复制到输出目录"。
关键注意事项
  • 禁止混用Worker和WebJobs SDK:.NET Framework4.8仅支持WebJobs SDK(v1或v4进程内);
  • 验证SOAP服务调用:确保使用svcutil.exe或Visual Studio"添加服务引用"生成正确的SOAP客户端,避免XML payload嵌套问题;
  • 注意NuGet版本兼容:安装包时需选择适配.NET Framework4.8的版本,避免版本冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 09:38:07