asp.net core web api 生成 swagger 文档

原文: asp.net core web api 生成 swagger 文档

asp.net core web api 生成 swagger 文档

Intro

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

集成 swagger

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

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

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

  3. 配置 web 项目使用 swaggerweb

    1. 配置 ConfigureServices,配置示例代码express

      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文档
      });
    2. 配置 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";
      });
    3. 如今从新启动项目,访问 "/swagger" 就能够看到效果了json

其余小技巧

  1. 忽略某些api,能够在controller 上加Attribute[ApiExplorerSettings(IgnoreApi = true)],这个Attribute 支持继承,也就是说你能够在一个BaseController 上加这个 Attribute ,这样继承于这个 BaseController 的 Controller 的接口都不会显示在 swagger 文档中后端

  2. 添加自定义请求头参数,能够自定义一个 OperationFilterapi

    1. 定义 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"
                  });
              }
          }
      }
    2. 配置 swagger 使用 OperationFilter

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

示例

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

swagger

这个API 接口文档只显示了API接口,服务器端其余的Controller 使用了上面提到的 [ApiExplorerSettings(IgnoreApi = true)] 忽略了

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

Reference

相关文章
相关标签/搜索