.NetCore【中间件】API文档Swagger

Swagger

为API接口生成文档

Core中添加Swagger

  1. nuget安装包
install-package Swashbuckle.AspNetCore
  1. 注册服务
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();

    
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { 
        Title = "My API", 
        Version = "v1" 
      });
        var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
        var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
        c.IncludeXmlComments(xmlPath, true); //添加控制器层注释(true表示显示控制器注释)
    });
}

  1. 使用服务

    // 启用中间件为生成的 JSON 文档和 Swagger UI 提供服务
    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", "My API V1");
     //c.RoutePrefix = string.Empty; 
    });

 

  1. 忽略XML注释警告

右键项目属性>生成>错误和警告添加 1591

源码

posted on 2022-12-05 21:46  杏村牧童  阅读(58)  评论(0编辑  收藏  举报