C# .net webapi使用swagger时显示controller注释

举报
清雨小竹 发表于 2022/09/25 00:21:52 2022/09/25
【摘要】 App_Start目录下新建SwaggerCacheProvider.cs using Swashbuckle.Swagger;using System;using System.Collections.Concurrent;using System.Collections.Generic;using System.IO;using ...

App_Start目录下新建SwaggerCacheProvider.cs


  
  1. using Swashbuckle.Swagger;
  2. using System;
  3. using System.Collections.Concurrent;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Web;
  8. using System.Xml;
  9. namespace YFAPICommon.App_Start
  10. {
  11. /// <summary>
  12. /// swagger 显示控制器的描述
  13. /// </summary>
  14. public class SwaggerCacheProvider : ISwaggerProvider
  15. {
  16. private readonly ISwaggerProvider _swaggerProvider;
  17. private static ConcurrentDictionary<string, SwaggerDocument> _cache = new ConcurrentDictionary<string, SwaggerDocument>();
  18. private readonly string _xmlPath;
  19. /// <summary>
  20. ///
  21. /// </summary>
  22. /// <param name="swaggerProvider"></param>
  23. /// <param name="xmlpath">xml文档路径</param>
  24. public SwaggerCacheProvider(ISwaggerProvider swaggerProvider, string xmlpath)
  25. {
  26. _swaggerProvider = swaggerProvider;
  27. _xmlPath = xmlpath;
  28. }
  29. public SwaggerDocument GetSwagger(string rootUrl, string apiVersion)
  30. {
  31. var cacheKey = string.Format("{0}_{1}", rootUrl, apiVersion);
  32. //只读取一次
  33. if (!_cache.TryGetValue(cacheKey, out SwaggerDocument srcDoc))
  34. {
  35. srcDoc = _swaggerProvider.GetSwagger(rootUrl, apiVersion);
  36. srcDoc.vendorExtensions = new Dictionary<string, object>
  37. {
  38. { "ControllerDesc", GetControllerDesc() }
  39. };
  40. _cache.TryAdd(cacheKey, srcDoc);
  41. }
  42. return srcDoc;
  43. }
  44. /// <summary>
  45. /// 从API文档中读取控制器描述
  46. /// </summary>
  47. /// <returns>所有控制器描述</returns>
  48. public ConcurrentDictionary<string, string> GetControllerDesc()
  49. {
  50. ConcurrentDictionary<string, string> controllerDescDict = new ConcurrentDictionary<string, string>();
  51. if (File.Exists(_xmlPath))
  52. {
  53. XmlDocument xmldoc = new XmlDocument();
  54. xmldoc.Load(_xmlPath);
  55. string[] arrPath;
  56. int cCount = "Controller".Length;
  57. foreach (XmlNode node in xmldoc.SelectNodes("//member"))
  58. {
  59. string type = node.Attributes["name"].Value;
  60. if (type.StartsWith("T:"))
  61. {
  62. arrPath = type.Split('.');
  63. string controllerName = arrPath[arrPath.Length - 1];
  64. if (controllerName.EndsWith("Controller")) //控制器
  65. {
  66. //获取控制器注释
  67. XmlNode summaryNode = node.SelectSingleNode("summary");
  68. string key = controllerName.Remove(controllerName.Length - cCount, cCount);
  69. if (summaryNode != null && !string.IsNullOrEmpty(summaryNode.InnerText) && !controllerDescDict.ContainsKey(key))
  70. {
  71. controllerDescDict.TryAdd(key, summaryNode.InnerText.Trim());
  72. }
  73. }
  74. }
  75. }
  76. }
  77. return controllerDescDict;
  78. }
  79. }
  80. }

2.项目根目录下添加swagger.js文件


  
  1. 'use strict';
  2. window.SwaggerTranslator = {
  3. _words: [],
  4. translate: function () {
  5. var $this = this;
  6. $('[data-sw-translate]').each(function () {
  7. $(this).html($this._tryTranslate($(this).html()));
  8. $(this).val($this._tryTranslate($(this).val()));
  9. $(this).attr('title', $this._tryTranslate($(this).attr('title')));
  10. });
  11. },
  12. setControllerSummary: function () {
  13. $.ajax({
  14. type: "get",
  15. async: true,
  16. url: $("#input_baseUrl").val(),
  17. dataType: "json",
  18. success: function (data) {
  19. var summaryDict = data.ControllerDesc;
  20. var id, controllerName, strSummary;
  21. $("#resources_container .resource").each(function (i, item) {
  22. id = $(item).attr("id");
  23. if (id) {
  24. controllerName = id.substring(9);
  25. strSummary = summaryDict[controllerName];
  26. if (strSummary) {
  27. $(item).children(".heading").children(".options").first().prepend('<li class="controller-summary" style="font-weight: bold;" title="' + strSummary + '">' + strSummary + '</li>');
  28. }
  29. }
  30. });
  31. }
  32. });
  33. },
  34. _tryTranslate: function (word) {
  35. return this._words[$.trim(word)] !== undefined ? this._words[$.trim(word)] : word;
  36. },
  37. learn: function (wordsMap) {
  38. this._words = wordsMap;
  39. }
  40. };
  41. /* jshint quotmark: double */
  42. window.SwaggerTranslator.learn({
  43. "Warning: Deprecated": "警告:已过时",
  44. "Implementation Notes": "实现备注",
  45. "Response Class": "响应类",
  46. "Status": "状态",
  47. "Parameters": "参数",
  48. "Parameter": "参数",
  49. "Value": "值",
  50. "Description": "描述",
  51. "Parameter Type": "参数类型",
  52. "Data Type": "数据类型",
  53. "Response Messages": "响应消息",
  54. "HTTP Status Code": "HTTP 状态码",
  55. "Reason": "原因",
  56. "Response Model": "响应模型",
  57. "Request URL": "请求 URL",
  58. "Response Body": "响应体",
  59. "Response Code": "响应码",
  60. "Response Headers": "响应头",
  61. "Hide Response": "隐藏响应",
  62. "Headers": "头",
  63. "Try it out!": "试一下!",
  64. "Show/Hide": "显示/隐藏",
  65. "List Operations": "显示操作",
  66. "Expand Operations": "展开操作",
  67. "Raw": "原始",
  68. "can't parse JSON. Raw result": "无法解析 JSON。原始结果",
  69. "Model Schema": "模型架构",
  70. "Model": "模型",
  71. "apply": "应用",
  72. "Username": "用户名",
  73. "Password": "密码",
  74. "Terms of service": "服务条款",
  75. "Created by": "创建者",
  76. "See more at": "查看更多:",
  77. "Contact the developer": "联系开发者",
  78. "api version": "api 版本",
  79. "Response Content Type": "响应 Content Type",
  80. "fetching resource": "正在获取资源",
  81. "fetching resource list": "正在获取资源列表",
  82. "Explore": "浏览",
  83. "Show Swagger Petstore Example Apis": "显示 Swagger Petstore 示例 Apis",
  84. "Can't read from server. It may not have the appropriate access-control-origin settings.": "无法从服务器读取。可能没有正确设置 access-control-origin。",
  85. "Please specify the protocol for": "请指定协议:",
  86. "Can't read swagger JSON from": "无法读取 swagger JSON于",
  87. "Finished Loading Resource Information. Rendering Swagger UI": "已加载资源信息。正在渲染 Swagger UI",
  88. "Unable to read api": "无法读取 api",
  89. "from path": "从路径",
  90. "server returned": "服务器返回"
  91. });
  92. $(function () {
  93. window.SwaggerTranslator.translate();
  94. window.SwaggerTranslator.setControllerSummary();
  95. });

3.将swagger.js设置成嵌入式资源

 

4.SwaggerConfig.cs文件里更改配置


  
  1. GlobalConfiguration.Configuration
  2. .EnableSwagger(c =>
  3. {
  4. c.CustomProvider((defaultProvider) => new SwaggerCacheProvider(defaultProvider, System.String.Format(@"{0}\bin\YFAPICommon.XML", System.AppDomain.CurrentDomain.BaseDirectory)));
  5. })
  6. .EnableSwaggerUi(c =>
  7. {
  8. c.InjectJavaScript(System.Reflection.Assembly.GetExecutingAssembly(), "YFAPICommon.swagger.js");
  9. });

效果:

 

文章来源: zzzili.blog.csdn.net,作者:清雨小竹,版权归原作者所有,如需转载,请联系作者。

原文链接:zzzili.blog.csdn.net/article/details/124445199

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。