Asp.NetCore WebApi 引入Swagger

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

二、引入NuGet包 SwashBuckle.AspNetCore 

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

 

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

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

 1 public void ConfigureServices(IServiceCollection services)
 2         {
 3             services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
 4 
 5             services.AddSwaggerGen(sg=>{
 6                 sg.SwaggerDoc("v1", new Info()
 7                 {
 8                     Version="1.0.0",
 9                     Title="WebApi",
10                     Description = "WebApi接口说明文档",
11                     TermsOfService = "None",
12                     Contact = new Contact
13                     {
14                         Name = "你是我的四月天",
15                         Email = "993484167@qq.com",
16                         Url = "https://www.cnblogs.com/awaTangjay/"
17                     }
18                 });
19                 sg.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "WebApi.xml"));//WebApi.xml是在项目属性配置中配置的xml文件名
20             });
21         }

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
        }

五、给控制器前加上路由

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

 六、ctrl+F5 调试WebApi

 在域名后面输入swagger 回车

 

posted @ 2019-01-18 10:37  你是我的四月天  阅读(496)  评论(0编辑  收藏  举报