• WebApi结合Swagger ui 实现在线接口文档


    基于Swagger 实现 webapi 自动生成在线测试文档

    Step1 添加NuGet包 Swashbuckle

    step2 修改SwaggerConfig.cs

       Swasshbuckle 安装完成之后会在App_Start下创建一个名为SwaggerConfig.cs的类,把内容替换为:

     1 using System.Web.Http;
     2 using WebActivatorEx;
     3 using SqlSugar.WebApi;
     4 using Swashbuckle.Application;
     5 using WebApi;
     6 
     7 [assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]
     8 
     9 namespace SqlSugar.WebApi
    10 {
    11     /// <summary>
    12     /// SwaggerConfig
    13     /// </summary>
    14     public class SwaggerConfig
    15     {
    16         /// <summary>
    17         /// Register
    18         /// </summary>
    19         public static void Register()
    20         {
    21             var thisAssembly = typeof(SwaggerConfig).Assembly;
    22 
    23             GlobalConfiguration.Configuration
    24                 .EnableSwagger(c =>
    25                     {
    26                         c.SingleApiVersion("v1", "SqlSugar.WebApi");
    27                         c.IncludeXmlComments(GetXmlCommentsPath());
    28                         c.OperationFilter<HttpHeaderFilter>(); 
    29                     })
    30                 .EnableSwaggerUi(c =>
    31                     {
    32                         // Use the "InjectStylesheet" option to enrich the UI with one or more additional CSS stylesheets.
    33                         // The file must be included in your project as an "Embedded Resource", and then the resource's
    34                         // "Logical Name" is passed to the method as shown below.
    35                         //
    36                         //c.InjectStylesheet(containingAssembly, "Swashbuckle.Dummy.SwaggerExtensions.testStyles1.css");
    37 
    38                         // Use the "InjectJavaScript" option to invoke one or more custom JavaScripts after the swagger-ui
    39                         // has loaded. The file must be included in your project as an "Embedded Resource", and then the resource's
    40                         // "Logical Name" is passed to the method as shown above.
    41                         //
    42                         //c.InjectJavaScript(thisAssembly, "Swashbuckle.Dummy.SwaggerExtensions.testScript1.js");
    43 
    44                         // The swagger-ui renders boolean data types as a dropdown. By default, it provides "true" and "false"
    45                         // strings as the possible choices. You can use this option to change these to something else,
    46                         // for example 0 and 1.
    47                         //
    48                         //c.BooleanValues(new[] { "0", "1" });
    49 
    50                         // By default, swagger-ui will validate specs against swagger.io's online validator and display the result
    51                         // in a badge at the bottom of the page. Use these options to set a different validator URL or to disable the
    52                         // feature entirely.
    53                         //c.SetValidatorUrl("http://localhost/validator");
    54                         //c.DisableValidator();
    55 
    56                         // Use this option to control how the Operation listing is displayed.
    57                         // It can be set to "None" (default), "List" (shows operations for each resource),
    58                         // or "Full" (fully expanded: shows operations and their details).
    59                         //
    60                         //c.DocExpansion(DocExpansion.List);
    61 
    62                         // Use the CustomAsset option to provide your own version of assets used in the swagger-ui.
    63                         // It's typically used to instruct Swashbuckle to return your version instead of the default
    64                         // when a request is made for "index.html". As with all custom content, the file must be included
    65                         // in your project as an "Embedded Resource", and then the resource's "Logical Name" is passed to
    66                         // the method as shown below.
    67                         //
    68                         //c.CustomAsset("index", containingAssembly, "YourWebApiProject.SwaggerExtensions.index.html");
    69 
    70                         // If your API has multiple versions and you've applied the MultipleApiVersions setting
    71                         // as described above, you can also enable a select box in the swagger-ui, that displays
    72                         // a discovery URL for each version. This provides a convenient way for users to browse documentation
    73                         // for different API versions.
    74                         //
    75                         //c.EnableDiscoveryUrlSelector();
    76 
    77                         // If your API supports the OAuth2 Implicit flow, and you've described it correctly, according to
    78                         // the Swagger 2.0 specification, you can enable UI support as shown below.
    79                         //
    80                         //c.EnableOAuth2Support("test-client-id", "test-realm", "Swagger UI");
    81                     });
    82         }
    83 
    84         private static string GetXmlCommentsPath()
    85         {
    86             return System.String.Format(@"{0}/App_Data/SqlSugar.WebApi.XML", System.AppDomain.CurrentDomain.BaseDirectory);
    87         }
    88     }
    89 }
    View Code

    Step3  创建生成XML

    右键你的项目→属性→生成→选中下方的 "XML文档文件" 然后保存

     step4 启动你的项目

       访问地址为:http://localhost:58192/swagger/

    扩展:在Swagger中 实现 自定义 HTTP Header

    在开发移动端 API时常常需要验证权限,验证参数放在Http请求头中是再好不过了。WebAPI配合过滤器验证权限即可

    首先我们需要创建一个 IOperationFilter 接口的类。IOperationFilter:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Http;
    using System.Web.Http.Description;
    using System.Web.Http.Filters;
    using Swashbuckle.Swagger;
    namespace WebApi
    {
        public class HttpHeaderFilter : IOperationFilter
        {
            public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    
            {
                if (operation.parameters == null)
                    operation.parameters = new List<Parameter>();
                var filterPipeline = apiDescription.ActionDescriptor.GetFilterPipeline(); //判断是否添加权限过滤器
                var isAuthorized = filterPipeline.Select(filterInfo => filterInfo.Instance).Any(filter => filter is IAuthorizationFilter); //判断是否允许匿名方法 
                var allowAnonymous = apiDescription.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any();
                if (isAuthorized && !allowAnonymous)
                {
                    operation.parameters.Add(new Parameter { name = "Authorization", @in = "header", description = "Token", required = false, type = "string" });
                }
            }
        }
    }

    在 SwaggerConfig.cs 的 EnableSwagger 配置匿名方法类添加一行注册代码

    c.OperationFilter<HttpHeaderFilter>();
    

    接上篇token验证中的权限过滤 地址:http://www.cnblogs.com/dukang1991/articles/5627584.html

    添加权限过滤器

    运行 swagger


    j

  • 相关阅读:
    套接字(socket)
    网络编程
    面向对象之反射
    面向对象的多态
    面向对象之封装
    面向对象之继承
    面向对象之编程思想
    python中的包
    python中的序列化模块
    正则表达式
  • 原文地址:https://www.cnblogs.com/dukang1991/p/5627673.html
Copyright © 2020-2023  润新知