webapi中构建Swagger

1、在Nuget程序包中搜索:Swagger

2、找到以下内容安装

/*----------------------------分割线-------------------------*/

3、运行项目 http://localhost:57407/swagger/ui/index

这个时候是跑不起来的,会提示报错信息,此时需要将SwaggerNet.cs中的代码注释

4、此时再运行就可以看到页面了,页面是有了,但是都是英文,备注信息也没有,我们需要在项目中打开xml注释,注释信息放在汉化里面一起解决。

ps:你会发现打开注释后,出现很多警告,可以设置取消1591,看个人需要。

ps:不知道有人是不是新建的demo,此时你还需要配置一下路由,否则页面只有控制器名而没有方法。

5、最终效果如图

6、看着这玩意到处都是英文,想要汉化的请举手

🙋🙋🙋🙋🙋🙋🙋🙋🙋🙋🙋🙋🙋...

--打开SwaggerConfig.cs,你会发现里面很多注释内容,虽然看着碍眼,但先不急着删,我们需要靠里面的内容来检索

搜索IncludeXmlComments,取消注释,实现GetXmlCommentsPath方法

        private static string GetXmlCommentsPath()
        {
            //之前修改的项目属性那里的地址
            return string.Format("{0}/bin/webapiSwagger.xml", System.AppDomain.CurrentDomain.BaseDirectory);
        }

7、效果如图,虽然注释信息汉化了,但是页面内容还是英文

8、添加汉化支持

  --8.1 添加汉化支持脚本swagger_lang.js,文件属性中的生成操作修改为【嵌入的资源】

  --脚本弄完后,打开 SwaggerConfig.cs 类 ,找到函数:InjectJavaScript,取消注释,并修改成上边自定义的js文件路径,格式用点分开

        c.InjectJavaScript(thisAssembly, "Swashbuckle.Dummy.SwaggerExtensions.testScript1.js");  原始内容

   c.InjectJavaScript(thisAssembly, "webapiSwagger.Swagger.swagger_lang.js");

js脚本

'use strict';
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')));
        });
    },

    setControllerSummary: function () {
        $.ajax({
            type: "get",
            async: true,
            url: $("#input_baseUrl").val(),
            dataType: "json",
            success: function (data) {
                var summaryDict = data.ControllerDesc;
                var id, controllerName, strSummary;
                $("#resources_container .resource").each(function (i, item) {
                    id = $(item).attr("id");
                    if (id) {
                        controllerName = id.substring(9);
                        strSummary = summaryDict[controllerName];
                        if (strSummary) {
                            $(item).children(".heading").children(".options").first().prepend('<li class="controller-summary" title="' + strSummary + '">' + strSummary + '</li>');
                            //颜色样式设置
                            $(".controller-summary").css({ "color": "red", "font-weight": "800" });
                        }
                    }
                });
            }
        });
    },
    _tryTranslate: function (word) {
        return this._words[$.trim(word)] !== undefined ? this._words[$.trim(word)] : word;
    },

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


/* jshint quotmark: double */
window.SwaggerTranslator.learn({
    "Warning: Deprecated": "警告:已过时",
    "Implementation Notes": "实现备注",
    "Response Class": "响应类",
    "Status": "状态",
    "Parameters": "参数",
    "Parameter": "参数",
    "Value": "值",
    "Description": "描述",
    "Parameter Type": "参数类型",
    "Data Type": "数据类型",
    "Response Messages": "响应消息",
    "HTTP Status Code": "HTTP状态码",
    "Reason": "原因",
    "Response Model": "响应模型",
    "Request URL": "请求URL",
    "Response Body": "响应体",
    "Response Code": "响应码",
    "Response Headers": "响应头",
    "Hide Response": "隐藏响应",
    "Headers": "头",
    "Try it out!": "试一下!",
    "Show/Hide": "显示/隐藏",
    "List Operations": "显示操作",
    "Expand Operations": "展开操作",
    "Raw": "原始",
    "can't parse JSON.  Raw result": "无法解析JSON. 原始结果",
    "Model Schema": "模型架构",
    "Model": "模型",
    "apply": "应用",
    "Username": "用户名",
    "Password": "密码",
    "Terms of service": "服务条款",
    "Created by": "创建者",
    "See more at": "查看更多:",
    "Contact the developer": "联系开发者",
    "api version": "api版本",
    "Response Content Type": "响应Content Type",
    "fetching resource": "正在获取资源",
    "fetching resource list": "正在获取资源列表",
    "Explore": "浏览",
    "Show Swagger Petstore Example Apis": "显示 Swagger Petstore 示例 Apis",
    "Can't read from server.  It may not have the appropriate access-control-origin settings.": "无法从服务器读取。可能没有正确设置access-control-origin。",
    "Please specify the protocol for": "请指定协议:",
    "Can't read swagger JSON from": "无法读取swagger JSON于",
    "Finished Loading Resource Information. Rendering Swagger UI": "已加载资源信息。正在渲染Swagger UI",
    "Unable to read api": "无法读取api",
    "from path": "从路径",
    "server returned": "服务器返回"
});
$(function () {
    window.SwaggerTranslator.translate();
    window.SwaggerTranslator.setControllerSummary();
});

  --8.2 添加控制器描述文件和接口文档缓存

    /// <summary>
    /// swagger显示控制器的描述
    /// </summary>
    public class SwaggerCacheProvider : ISwaggerProvider
    {
        private readonly ISwaggerProvider _swaggerProvider;
        private static ConcurrentDictionary<string, SwaggerDocument> _cache = new ConcurrentDictionary<string, SwaggerDocument>();
        private readonly string _xml;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="swaggerProvider"></param>
        /// <param name="xml">xml文档路径</param>
        public SwaggerCacheProvider(ISwaggerProvider swaggerProvider, string xml)
        {
            _swaggerProvider = swaggerProvider;
            _xml = xml;
        }

        public SwaggerDocument GetSwagger(string rootUrl, string apiVersion)
        {

            var cacheKey = string.Format("{0}_{1}", rootUrl, apiVersion);
            SwaggerDocument srcDoc = null;
            //只读取一次
            if (!_cache.TryGetValue(cacheKey, out srcDoc))
            {
                srcDoc = _swaggerProvider.GetSwagger(rootUrl, apiVersion);

                srcDoc.vendorExtensions = new Dictionary<string, object> { { "ControllerDesc", GetControllerDesc() } };
                _cache.TryAdd(cacheKey, srcDoc);
            }
            return srcDoc;
        }

        /// <summary>
        /// 从API文档中读取控制器描述
        /// </summary>
        /// <returns>所有控制器描述</returns>
        public ConcurrentDictionary<string, string> GetControllerDesc()
        {
            string xmlpath = _xml;
            ConcurrentDictionary<string, string> controllerDescDict = new ConcurrentDictionary<string, string>();
            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;
        }
    }
View Code

  找到在SwaggerConfig.cs文件中检索CustomProvider,重新定义该行内容为

       c.CustomProvider((defaultProvider) => new SwaggerCacheProvider(defaultProvider, string.Format("{0}/bin/webapiSwagger.xml", System.AppDomain.CurrentDomain.BaseDirectory)));

另外:对于想要返回实体模型的注释,需要额外指定;如果实体模型与当前项目不再同一项目,需要添加model的xml地址

//添加方法修饰属性返回类型说明
[SwaggerResponse(HttpStatusCode.OK, Type = typeof(Models.NewsInfo))]

总结,拼凑文大家将就着看一下,我也是第一次弄,之前看了一个java的前端UI框架,使用的也是swagger,看到别人的api文档顿感优雅,心里只有一个念想:我也要!

posted @ 2021-04-23 15:31  汉中欸  阅读(116)  评论(0编辑  收藏  举报