您的位置:首页 > 编程语言 > ASP

asp.net core web api 生成 swagger 文档

2019-07-04 10:51 971 查看

asp.net core web api 生成 swagger 文档

Intro

在前后端分离的开发模式下,文档就显得比较重要,哪个接口要传哪些参数,如果一两个接口还好,口头上直接沟通好就可以了,如果接口多了就有点不适用了,没有接口文档会大大提高前后端的沟通成本。而 asp.net core 可以通过 Swashbuckle.AspNetCore 很方便的集成 swagger 文档,相比之下 nodejs(express) 和 swagger 集成就很麻烦了,大概这就是强类型语言的优势吧。C# 是最好的编程语言~~~

集成 swagger

  1. 配置 model 以及 api 项目生成 xml 文档

    在对应项目的项目文件中加入下面的代码,配置生成 xml 文档

    <PropertyGroup>
    <GenerateDocumentationFile>true</GenerateDocumentationFile>
    <NoWarn>$(NoWarn);1591</NoWarn>
    </PropertyGroup>
  2. 在 Web 项目上引用

    Swashbuckle.AspNetCore

  3. 配置 web 项目使用 swagger

    配置 ConfigureServices,配置示例代码

    services.AddSwaggerGen(options =>
    {
    options.SwaggerDoc(ApplicationHelper.ApplicationName, new Info { Title = "活动室预约系统 API", Version = "1.0" });
    
    options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{typeof(Notice).Assembly.GetName().Name}.xml")); //使用Model项目的xml文档
    options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{typeof(NoticeController).Assembly.GetName().Name}.xml"), true); //使用ApiController项目的xml文档
    });
  4. 配置 Configure ,配置示例代码

    app
    .UseSwagger()
    .UseSwaggerUI(c =>
    {
    // c.RoutePrefix = string.Empty; //配置swagger ui前缀,默认值是 "swagger",你可以使用 "string.Empty"来配置首页就是 swagger ui
    c.SwaggerEndpoint($"/swagger/{ApplicationHelper.ApplicationName}/swagger.json", "活动室预约系统 API");
    c.DocumentTitle = "活动室预约系统 API";
    });
  5. 现在重新启动项目,访问 "/swagger" 就可以看到效果了

其他小技巧

  1. 忽略某些api,可以在controller 上加Attribute

    [ApiExplorerSettings(IgnoreApi = true)]
    ,这个Attribute 支持继承,也就是说你可以在一个BaseController 上加这个 Attribute ,这样继承于这个 BaseController 的 Controller 的接口都不会显示在 swagger 文档中

  2. 添加自定义请求头参数,可以自定义一个 OperationFilter

    定义 OperationFilter 示例

    public class AuthorizationOperationFilter : IOperationFilter
    {
    public void Apply(Operation operation, OperationFilterContext context)
    {
    if (operation.Parameters == null)
    {
    operation.Parameters = new List<IParameter>();
    }
    var filterPipeline = context.ApiDescription.ActionDescriptor.FilterDescriptors;
    var isAuthorized = filterPipeline.Any(filter => filter.Filter is AuthorizeFilter);
    var allowAnonymous = filterPipeline.Any(filter => filter.Filter is IAllowAnonymousFilter);
    
    if (isAuthorized && !allowAnonymous)
    {
    operation.Parameters.Add(new NonBodyParameter()
    {
    Name = "Authorization",
    In = "header",
    Type = "string",
    Description = "access token",
    Required = true
    });
    }
    }
    }
    
    public class ApiVersionOperationFilter : IOperationFilter
    {
    public void Apply(Operation operation, OperationFilterContext context)
    {
    if (operation.Parameters == null)
    {
    operation.Parameters = new List<IParameter>();
    }
    context.ApiDescription.TryGetMethodInfo(out var methodInfo);
    
    if (methodInfo.DeclaringType.IsDefined(typeof(ApiVersionAttribute), true))
    {
    operation.Parameters.Add(new NonBodyParameter()
    {
    Name = "Api-Version",
    In = "header",
    Type = "string",
    Description = "Api-Version",
    Required = true,
    Default = "1.0"
    });
    }
    }
    }
  3. 配置 swagger 使用 OperationFilter

    services.AddSwaggerGen(options =>
    {
    // ...
    options.OperationFilter<AuthorizationOperationFilter>();
    });
  • 更多技术及骚操作参考官方文档介绍 https://github.com/domaindrivendev/Swashbuckle.AspNetCore

  • 示例

    API 接口 swagger 文档 https://reservation.weihanli.xyz/swagger/index.html

    这个API 接口文档只显示了API接口,服务器端其他的Controller 使用了上面提到的

    [ApiExplorerSettings(IgnoreApi = true)]
    忽略了

    最近我的活动室预约的项目增加了一个前后端分离的 angular + marterial 的客户端,体验地址 https://reservation-client.weihanli.xyz/

    Reference

    内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
    标签: