Asp.NetCore WebApi 引入Swagger

一、创建一个Asp.NetCore WebApi 项目

Asp.NetCore WebApi 引入Swagger

Asp.NetCore WebApi 引入Swagger

二、引入NuGet包 SwashBuckle.AspNetCore

Asp.NetCore WebApi 引入Swagger

三、在项目属性配置中设置

Asp.NetCore WebApi 引入Swagger

Asp.NetCore WebApi 引入Swagger

四、修改项目的启动文件Startup.cs

1)、在ConfigureServices方法中注册Swagger中间件

 public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddSwaggerGen(sg=>{
sg.SwaggerDoc("v1", new Info()
{
Version="1.0.0",
Title="WebApi",
Description = "WebApi接口说明文档",
TermsOfService = "None",
Contact = new Contact
{
Name = "你是我的四月天",
Email = "993484167@qq.com",
Url = "https://www.cnblogs.com/awaTangjay/"
}
});
sg.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "WebApi.xml"));//WebApi.xml是在项目属性配置中配置的xml文件名
});
}

2)、在Configure方法启用Swagger中间件

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
} app.UseHttpsRedirection();
app.UseMvc(); app.UseSwagger(s => s.RouteTemplate="swagger/{documentName}/swagger.json");
app.UseSwaggerUI(s => { s.SwaggerEndpoint("v1/swagger.json","v1.0.0"); });//这个v1对应SwaggerDoc中的name v1
}

Asp.NetCore WebApi 引入Swagger

五、给控制器前加上路由

[Route("api/[controller]/[Action]")]
[ApiController]
public class ValuesController : ControllerBase
{

六、ctrl+F5 调试WebApi

在域名后面输入swagger 回车

Asp.NetCore WebApi 引入Swagger

Asp.NetCore WebApi 引入Swagger

上一篇:Java注解(Annotation)用法:利用注解和反射机制指定列名导出数据库数据


下一篇:IMoniker接口的MKParseDisplayName和 GetDisplayName的注意事项