Swashbuckle for asp.net core 配置说明

0x00 安装 Swashbuckle 6.0

打开程序包管理器控制台,输入:

Install-Package Swashbuckle -Pre

0x01 配置 Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddApplicationInsightsTelemetry(Configuration);
    services.AddMvc();
    // 下面是具体的配置
    services.AddSwaggerGen(c =>
    {
        c.SingleApiVersion(new Info
        {
            Version = "v1",     // 这个属性必须要填,否则会引发一个异常
            Title = "BookList API 文档",
            Description = "书单的 API 文档"
        });
    });

    services.ConfigureSwaggerGen(c =>
    {
        // 配置生成的 xml 注释文档路径
        c.IncludeXmlComments(GetXmlCommentsPath());
    });
}


public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseApplicationInsightsRequestTelemetry();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseApplicationInsightsExceptionTelemetry();

    app.UseStaticFiles();

    app.UseSwagger();
    app.UseSwaggerUi("doc/api");    // 配置 api 文档的访问路径

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

下面是获取xml文档路径的方法

private string GetXmlCommentsPath()
{
    var app = PlatformServices.Default.Application;
    return Path.Combine(app.ApplicationBasePath, Path.ChangeExtension(app.ApplicationName, "xml"));
}

0x03 配置项目属性

在 VS 的菜单中,项目 -- 属性 -- 生成 -- Output -- XML documentation file 打上勾

0x04 尽情使用生成的文档吧!

访问 localhost:*****/doc/api 就可以看到生成的文档
这里的路径是我在上面配置的,默认的路径是 swagger/ui


参考:https://github.com/domaindrivendev/Ahoy

posted @ 2016-07-31 12:08  不如隐茶去  阅读(1903)  评论(1编辑  收藏  举报