zoukankan      html  css  js  c++  java
  • 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. 直接配置使用全局Auth

         options.AddSecurityDefinition("Bearer", new ApiKeyScheme
         {
             Name = "Authorization",
             In = "header",
             Description = "Bearer token"
         });
         options.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
         {
             { "Bearer", Enumerable.Empty<string>() }
         });
        
    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

  • 相关阅读:
    [LeetCode 题解]: Remove Duplicates from Sorted List
    [LeetCode 题解]: Merge k Sorted Lists
    [LeetCode 题解]: Insertion Sort List
    [LeetCode 题解]:Candy
    求任意多边形面积 python实现
    C++飞机大战
    version robot
    python一段代码 感受一下
    微机原理上机第四次实验内容
    初步的百度爬虫
  • 原文地址:https://www.cnblogs.com/weihanli/p/generate-swagger-for-aspnetcore-api.html
Copyright © 2011-2022 走看看