.NET 7 Azure Functions V4(孤立进程)集成Swashbuckle Swagger中间件的实现指导咨询
你好!针对你在孤立进程Azure Functions V4中集成Swagger的问题,我来帮你梳理下正确的实现方式,同时解答你的疑问:
首先要明确:孤立进程模式的Azure Functions和Web API/进程内模式的Functions不一样,不能直接用IApplicationBuilder的UseSwagger()/UseSwaggerUI()方法,不过你不用自己手动实现IFunctionsWorkerMiddleware——官方已经为孤立进程封装了专门的Swagger集成扩展,就是你已经引用的Microsoft.Azure.Functions.Worker.Extensions.OpenApi包,直接用它提供的方法就可以搞定。
具体实现步骤
确认NuGet包安装
确保你已经安装了正确版本的Microsoft.Azure.Functions.Worker.Extensions.OpenApi(版本建议和Microsoft.Azure.Functions.Worker保持一致,比如最新稳定版)。在Worker配置中添加Swagger中间件
在ConfigureFunctionsWorkerDefaults方法里,通过IFunctionsWorkerApplicationBuilder(也就是代码里的worker对象)添加OpenApi相关中间件,同时可以结合环境判断只在开发环境启用Swagger UI:.ConfigureFunctionsWorkerDefaults((context, worker) => { worker.UseNewtonsoftJson(); worker.UseMiddleware<AuthorizationMiddleware>(); // 仅在开发环境启用Swagger相关功能 if (context.HostingEnvironment.IsDevelopment()) { // 暴露Swagger JSON文档端点 worker.UseOpenApi(options => { // 可以自定义文档路由,默认是 /swagger/{documentName}/swagger.json options.RoutePrefix = "swagger"; }); // 启用Swagger UI界面 worker.UseSwaggerUI(options => { options.SwaggerEndpoint("/swagger/v1/swagger.json", "Sample V1"); // 自定义UI的路由前缀,默认是 swagger options.RoutePrefix = "swagger"; }); } })保留现有SwaggerGen配置
你已经写的services.AddSwaggerGen(...)部分完全没问题,这部分负责生成Swagger文档的元数据、安全方案(比如你配置的Bearer认证)等,和中间件是互补的。
关于你提到的自定义IFunctionsWorkerMiddleware的疑问
理论上,你自己实现IFunctionsWorkerMiddleware来处理Swagger是可行的,但需要自己处理很多细节:比如读取SwaggerGen生成的文档、提供Swagger UI的静态文件、处理路由映射等。官方的UseOpenApi()和UseSwaggerUI()已经封装了所有这些逻辑,完全没必要重复造轮子,用官方扩展是最省心可靠的选择。
修改后的完整代码示例
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Azure.Functions.Worker.Extensions.OpenApi.Extensions; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.OpenApi.Models; using System.Collections.Generic; var host = new HostBuilder() .ConfigureFunctionsWorkerDefaults((context, worker) => { worker.UseNewtonsoftJson(); worker.UseMiddleware<AuthorizationMiddleware>(); // 仅在开发环境启用Swagger if (context.HostingEnvironment.IsDevelopment()) { worker.UseOpenApi(); worker.UseSwaggerUI(options => { options.SwaggerEndpoint("/swagger/v1/swagger.json", "Sample V1"); options.RoutePrefix = "swagger"; }); } }) .ConfigureServices(services => { services.AddLocalClients(); services.AddWorkerServices(); services.AddApplicationInsightsTelemetryWorkerService(); services.AddSwaggerGen(options => { options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Description = "JWT Authorization header using the Bearer scheme. \r\n\r\n " + "Enter 'Bearer' [space] and then your token in the text input below.\r\n\r\n" + "Example: \"Bearer 12345abcdef\"", Name = "Authorization", In = ParameterLocation.Header, Scheme = "Bearer" }); options.AddSecurityRequirement(new OpenApiSecurityRequirement() { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }, Scheme = "oauth2", Name = "Bearer", In = ParameterLocation.Header }, new List<string>() } }); options.SwaggerDoc("v1", new OpenApiInfo { Version = "v1.0", Title = "Sample V1", Description = "API to manage XXXXX", TermsOfService = new Uri("https://example.com/terms"), Contact = new OpenApiContact { Name = "xxxxxx", Url = new Uri("https://example.com") }, License = new OpenApiLicense { Name = "Example License", Url = new Uri("https://example.com/license") } }); }); }) .ConfigureAppConfiguration((hostContext, config) => { config.AddJsonFile("appsettings.json", optional: true); }) .ConfigureLogging((hostingContext, logging) => { logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); }) .Build(); host.Run();
验证效果
启动函数应用后,在开发环境访问 http://localhost:<你的端口>/swagger 就能看到Swagger UI界面,http://localhost:<你的端口>/swagger/v1/swagger.json 可以获取Swagger JSON文档。
备注:内容来源于stack exchange,提问作者suraj_123

