美文网首页
.net core 2.1web api 集成Swagger

.net core 2.1web api 集成Swagger

作者: 守星的犬 | 来源:发表于2018-11-02 23:17 被阅读161次

通过Swagger可以把WEB API里的路由输出成网页形式的API文档。集成方法如下。

环境:.net core 2.1,VS社区版


首先添加Swagger依赖"Swashbuckle.AspNetCore"。


然后在Startup.cs中,把Swagger加入到中间件服务的列表中:

using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerUI;

public void ConfigureServices(IServiceCollection services)
{ 
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

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

}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseMvc();

    //配置Swagger-------------------//
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "DemoAPI V1");
    });
}

编译项目,在浏览器中访问:https://localhost:5001/swagger

相关文章

网友评论

      本文标题:.net core 2.1web api 集成Swagger

      本文链接:https://www.haomeiwen.com/subject/cjyhxqtx.html