asp.net core web api 生成 swagger 文档

Posted weihanli

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了asp.net core web api 生成 swagger 文档相关的知识,希望对你有一定的参考价值。

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

    1. 配置 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文档
      );
    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" 就可以看到效果了

其他小技巧

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

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

    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

技术图片

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

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

Reference

以上是关于asp.net core web api 生成 swagger 文档的主要内容,如果未能解决你的问题,请参考以下文章

ASP.NET Core Web Api 自动帮助页面

JWT不记名令牌授权不起作用asp net core web api

Refit结合Polly访问ASP.NET Core Web API

ASP.NET Core Web API使用静态swagger.json文件

如何使用 Web Api Asp.Net Core 实现基于声明的授权?

将文件从 ASP.NET Core Web api 发布到另一个 ASP.NET Core Web api