Visual studio code整合Swagger-ui简易方法

  • 1、首先我们需要安装swagger-ui依赖包

在终端控制台输入命令:dotnet add YourProjectName.csproj package Swashbuckle.AspNetCore

  • 2、添加配置和Swagger中间件

在Startup.cs文件的ConfigureServices方法内添加代码如下:

// Register the Swagger generator, defining 1 or more Swagger documents

services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "CqingForumAPI", Version = "v1" }); });

且引用命名空间:using Swashbuckle.AspNetCore.Swagger;

在Startup.cs文件的Configure方法内添加代码如下:

 

// Enable middleware to serve generated Swagger as a JSON endpoint.

app.UseSwagger();

// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),

// specifying the Swagger JSON endpoint.

app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "CqingForumAPI V1"); });


到这里visual studio code整合Swagger-ui基本算完事了。这是简化过后的方法,具体方法可以查看官方网站的介绍Visual Studio Code整合Swagger-UI详细

最后,你直接直接启动项目。浏览器输入https://localhost:xxxx/swagger,即可看到效果。若页面显示无所有api,可能是你路由没有配置好。

这是我配置好的效果图:


补充:这里好像还没有对API的方法相关进行备注说明,例如summary信息未显示,加上下列代码即可:

先在ProjectName.csproj文件里节点PropertyGroup内添加代码:

<GenerateDocumentationFile>true</GenerateDocumentationFile>

<NoWarn>$(NoWarn);1591</NoWarn>

然后在StartUp.cs文件内方法ConfigureServices的services.AddSwaggerGen内添加代码:

// Set the comments path for the Swagger JSON and UI.

var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";   //引用System.Reflection

var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); //引用System.IO;

c.IncludeXmlComments(xmlPath);

最后项目启动即可

附图:

猜你喜欢

转载自blog.csdn.net/zhangshineng/article/details/84852108
今日推荐