zoukankan      html  css  js  c++  java
  • C#中使用swagger小技巧

    C#中使用swagger小技巧 

    swaggerUI显示的接口内容主要用于开发阶段便于与前端联调,不适合发布到对外的站点。

    有以下两种方式,让接口不显示在SwaggerUI中

    1.使用属性 [ApiExplorerSettings(IgnoreApi = true)]设置接口不显示到swaggerUI,此方法比较灵活,可以根据情况在对于的控制器或者API接口中添加。

    列如:

        [ApiExplorerSettings(IgnoreApi = true)]

        public class SystemController : ApiController

        {   

    }

    这样编写,整个控制器中的接口都不会显示在swaggerUI,如果只是想针对某个接口不显示在UI中,可以在接口处增加属性,列如:

        public class SystemController : ApiController

        {

            [HttpGet]

            [ApiExplorerSettings(IgnoreApi = true)]

            public string GetSystemTime()

            {

                return DateTime.Now.ToString();

            }       

    }

    我们调试一般都会将编译类型选择为Debug,那么可以如下写:

    #if (!DEBUG)

        [ApiExplorerSettings(IgnoreApi = true)]

     #endif

    public class SystemController : ApiController

    {   

    }

    这样开发阶段就可以正常的查看swaggerUI,到发布到UAT或者其他环境时,选择Release类型编译发布即可。

    针对某个接口不显示在UI中,可以在接口处修改属性,列如:

        public class SystemController : ApiController

        {

            [HttpGet]

            #if (!DEBUG)

                [ApiExplorerSettings(IgnoreApi = true)]

    #endif

            public string GetSystemTime()

            {

                return DateTime.Now.ToString();

          }       

    }

    第二种方式:

    就是不加载SwaggerConfig文件,这样在发布就不会显示swaggerUI,列如:

    #if (DEBUG)

        [assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]

    #endif

    这样做的缺点是,接口说明都不显示了。

    可以通过自己的使用情况,选择合适的方式。

    寻寻觅觅转流年,磕磕碰碰道缘浅。 揽几缕、轻挽起,暮暮朝朝与君语。
  • 相关阅读:
    『Asp.Net 组件』第一个 Asp.Net 服务器组件:自己的文本框控件
    『Asp.Net 组件』Asp.Net 服务器组件 的开发优势和劣势
    『开源』简单的代码统计工具 开源啦[有图有真相]
    文件中的类都不能进行设计,因此未能为该文件显示设计器。设计器检查出文件中有以下类: FormMain --- 未能加载基类
    DB2:FETCH FIRST 1 ROWS ONLY
    IEnumerable的几个简单用法
    一个字符串中包含逗号个数
    字符串处理总结之一(C#String类)
    C# 中DateTime的各种使用
    C# 键值对类相关
  • 原文地址:https://www.cnblogs.com/bingshao/p/13606670.html
Copyright © 2011-2022 走看看