您现在的位置是:网站首页> 编程资料编程资料

NetCore 配置Swagger的详细代码_实用技巧_

2023-05-24 487人已围观

简介 NetCore 配置Swagger的详细代码_实用技巧_

1.添加Nuget

install-package Swashbuckle.AspNetCore -project XXX -version 6.4.0

2.添加静态类扩展方法

2.1.生成项目xml:选中项目 / 右键 / 属性 / 生成 / 输出 / 选中xml文档文件

2.2.system_v1:必须唯一不重复,且【options.SwaggerDoc("system_v1"】必须与【options.SwaggerEndpoint("/swagger/system_v1/】一致,不然会异常【Failed to load API definition; Fetch error: response status is 404 /swagger/system_v1/swagger.json】

///  /// Swagger 静态类 ///  public static class SwaggerExtend { ///  /// 添加服务: swagger ///  ///  ///  public static void AddCustSwagger(this IServiceCollection services) { var version = "V1.0"; var apiName = "XXX系统"; services.AddSwaggerGen(options => { options.ResolveConflictingActions(apiDescriptions => apiDescriptions.First()); options.SwaggerDoc("system_v1", new OpenApiInfo { Version = version, Title = $"{apiName} API", Description = $"{apiName} {version} 接口服务" }); // 获取应用程序所在目录 var basePath = Path.GetDirectoryName(typeof(SwaggerExtend).Assembly.Location); var xmlPath = Path.Combine(basePath, "ProjectName.xml"); // swagger界面默认只显示 方法&字段 注释,不显示 控制器注释 // 第二个参数为true, 则是controller的注释 //options.IncludeXmlComments(xmlPath); options.IncludeXmlComments(xmlPath, true); }); } ///  /// 添加中间件: swagger ///  ///  public static void UseCustSwagger(this IApplicationBuilder app) { app.UseSwagger(); app.UseSwaggerUI(options => { options.SwaggerEndpoint("/swagger/system_v1/swagger.json", "系统API"); // 默认路径为:/swagger/index.html // 路由前缀 - 设置为空,可直接跳转到swagger页面:/index.html // api测试可设置为空,部署时容易与前端路由冲突 options.RoutePrefix = string.Empty; }); } }

3.StartUp注册服务,添加中间件

public void ConfigureServices(IServiceCollection services) { services.AddCustSwagger(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseCustSwagger(); }

到此这篇关于NetCore 配置Swagger的的文章就介绍到这了,更多相关NetCore 配置Swagger内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

-六神源码网