swagger的作用和配置使用
阅读原文时间:2022年04月01日阅读:1

纯API项目中 引入swagger可以生成可视化的API接口页面

   


引入包

nuget包: Swashbuckle.AspNetCore(最新稳定版)

配置

1.配置Startup类ConfigureServices方法的相关配置

1 public void ConfigureServices(IServiceCollection services)
2 {
3 //swagger服务配置
4 services.AddSwaggerGen(c =>
5 {
6 c.SwaggerDoc("V1", new Microsoft.OpenApi.Models.OpenApiInfo
7 {
8 Version = "v1",//接口文档版本
9 Title = "我的接口文档1.0",//接口文档标题
10 Description = "我的第一个swagger文档",//接口文档描述
11 Contact = new Microsoft.OpenApi.Models.OpenApiContact { Name = "张华", Url = new Uri("http://baidu.com"), Email = "nice0320@163.com" },
12 License = new Microsoft.OpenApi.Models.OpenApiLicense { Name = "张华", Url = new Uri("http://baidu.com") }
13 });
14 });
15 services.AddControllers();
16 }

1.配置Startup类ConfigureServices方法的相关配置

2.配置Startup类Configure方法的中间件

1 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
2 {
3 if (env.IsDevelopment())
4 {
5 app.UseDeveloperExceptionPage();
6 }
7
8 app.UseRouting();
9
10 app.UseAuthorization();
11
12 app.UseEndpoints(endpoints =>
13 {
14 endpoints.MapControllers();
15 });
16
17 ///swagger中间件启动配置
18 app.UseSwagger();
19 app.UseSwaggerUI(a => {
20 a.SwaggerEndpoint("/swagger/V1/swagger.json", "中间件启动配置,我的第一个swagger文档");
21 //如果是为空 访问路径就为 根域名/index.html,注意localhost:8001/swagger是访问不到的
22 //路径配置,设置为空,表示直接在根域名(localhost:8001)访问该文件
23 // c.RoutePrefix = "swagger"; // 如果你想换一个路径,直接写名字即可,比如直接写c.RoutePrefix = "swagger"; 则访问路径为 根域名/swagger/index.html
24 a.RoutePrefix = string.Empty;//路由
25 });
26 }

2.配置Startup类Configure方法的中间件

新建项目第一次配置完成运行的时候可能如下所示。因为 /WeatherForecast 是官方默认的地址

解决方案:Properties文件夹下launchSettings.json文件launchUrl属性改为null

launchUrl代表浏览器里启动相对的URL


Ps:个人小小理解,希望有错误可以指正