自动生成 WebApi 在线说明文档。

2021-05-31 15:04

阅读:434

标签:sch   rop   状态码   put   方法   can   body   ogg   example   

1.使用Swashbuckle实现

Swashbuckle 是.NET类库,可以将WebAPI所有开放的控制器方法生成对应SwaggerUI的JSON配置。再通过SwaggerUI 显示出来。类库中已经包含SwaggerUI 。所以不需要额外安装。

2.快速开始。前提已有webapi项目

查看webapi项目属性,在【生成】选项卡中勾选X【ML文档文件】。在编译过程中会生成一个注释文件

  • 使用NuGet包将Swashbuckle库添加到在webapi项目中

技术图片

  • 引用后,在App_Start文件夹下会生成一个SwaggerConfig.cs配置文件。可以修改配置文件,实现自定义SwaggerUI相关展示行为等。

技术图片

  • 自定义swagger提供类,实现中文展示
 /// 
    /// 自定义swagger的控制器描述
    /// 
    public class SwaggerControllerDescProvider : ISwaggerProvider
    {
        private readonly ISwaggerProvider _swaggerProvider;
        private readonly string _xml;
        /// 

        /// 
        /// 
        /// 
        /// xml文档路径
        public SwaggerControllerDescProvider(ISwaggerProvider swaggerProvider, string xml)
        {
            _swaggerProvider = swaggerProvider;
            _xml = xml;
        }

        public SwaggerDocument GetSwagger(string rootUrl, string apiVersion)
        {
            SwaggerDocument srcDoc = null;
            srcDoc = _swaggerProvider.GetSwagger(rootUrl, apiVersion);
            srcDoc.vendorExtensions = new Dictionary { { "ControllerDesc", GetControllerDesc() } };
            return srcDoc;
        }

        /// 

        /// 从API文档中读取控制器描述
        /// 
        /// 所有控制器描述
        public ConcurrentDictionary GetControllerDesc()
        {
            string xmlpath = _xml;
            ConcurrentDictionary controllerDescDict = new ConcurrentDictionary();
            if (File.Exists(xmlpath))
            {
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load(xmlpath);
                string type = string.Empty, path = string.Empty, controllerName = string.Empty;

                string[] arrPath;
                int length = -1, cCount = "Controller".Length;
                XmlNode summaryNode = null;
                foreach (XmlNode node in xmldoc.SelectNodes("//member"))
                {
                    type = node.Attributes["name"].Value;
                    if (type.StartsWith("T:"))
                    {
                        //控制器
                        arrPath = type.Split(‘.‘);
                        length = arrPath.Length;
                        controllerName = arrPath[length - 1];
                        if (controllerName.EndsWith("Controller"))
                        {
                            //获取控制器注释
                            summaryNode = node.SelectSingleNode("summary");
                            string key = controllerName.Remove(controllerName.Length - cCount, cCount);
                            if (summaryNode != null && !string.IsNullOrEmpty(summaryNode.InnerText) && !controllerDescDict.ContainsKey(key))
                            {
                                controllerDescDict.TryAdd(key, summaryNode.InnerText.Trim());
                            }
                        }
                    }
                }
            }
            return controllerDescDict;
        }

    }
  •   添加js文件,实现中文展示等。注意:查看js文件属性,将生成操作改为【嵌入的资源】
‘use strict‘;

/**
 * Translator for documentation pages.
 *
 * To enable translation you should include one of language-files in your index.html
 * after .
 * For example - 
 *
 * If you wish to translate some new texsts you should do two things:
 * 1. Add a new phrase pair ("New Phrase": "New Translation") into your language file (for example lang/ru.js). It will be great if you add it in other language files too.
 * 2. Mark that text it templates this way New Phrase or .
 * The main thing here is attribute data-sw-translate. Only inner html, title-attribute and value-attribute are going to translate.
 *
 */
window.SwaggerTranslator = {
    
    _words: [],

    translate: function () {
        var $this = this;
        $(‘[data-sw-translate]‘).each(function () {
            $(this).html($this._tryTranslate($(this).html()));
            $(this).val($this._tryTranslate($(this).val()));
            $(this).attr(‘title‘, $this._tryTranslate($(this).attr(‘title‘)));
        });
    },

    _tryTranslate: function (word) {
        return this._words[$.trim(word)] !== undefined ? this._words[$.trim(word)] : word;
    },

    learn: function (wordsMap) {
        this._words = wordsMap;
    },

    setControllerSummary: function () {
        $.ajax({
            type: "get",
            async: true,
            url: $("#input_baseUrl").val(),
            dataType: "json",
            success: function (data) {
                //console.log(data)
                var toggleEndpointList = [];
                var summaryDict = data.ControllerDesc;
                var id, controllerName, strSummary;
                var s = $("#resources .resource");
                $("#resources .resource").each(function (i, item) {
                    id = $(item).attr("id");
                    if (id) {
                        controllerName = id.substring(9, 11) + "_" + id.substring(13);
                        strSummary = summaryDict[controllerName];
                        if (strSummary) {
                            console.log($(item))
                            $(item).children(".heading").children("h2").children(‘a‘).text(strSummary);
                            $(item).children(".heading").children(".options").prepend(‘
  • ‘ + strSummary + ‘
  • ‘); toggleEndpointList.push($(item).attr(‘id‘)) } } }); for (var i = 0; i
    • 运行http://ip:host/swagger/ui/index 查看效果

     

    自动生成 WebApi 在线说明文档。

    标签:sch   rop   状态码   put   方法   can   body   ogg   example   

    原文地址:https://www.cnblogs.com/Jenny-1/p/11011117.html


    评论


    亲,登录后才可以留言!