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

相關文章
相關標籤/搜索