如何通过JQuery完善SwaggerUI分组版本文档切换的SetVersionedGroup函数?
完善SwaggerUI自定义分组/版本选择器的SetVersionedGroup函数
你已经完成了自定义分组和版本选择器的UI渲染部分,现在只需要让选择器触发SwaggerUI切换对应的文档即可。下面是完善后的SetVersionedGroup函数,以及对应的逻辑说明:
完整的代码(包含完善后的函数)
(function (){ var DiscoveryUrlSelector = Backbone.View.extend({ render: function () { // 避免重复渲染(页面重载时) var defaultVal = this.$el.val() if (!this.$el.find('#input_' + this.options.name).length) { var select = $('<select id="input_' + this.options.name + '" name="' + this.options.name + '"></select>'); select .css('margin', '0px 10px 0px 0px') .css('border', '1px solid gray') .css('padding', '3px') .css('width', '100px') .css('font-size', '0.9em'); _.each(this.options.discoveryPaths, function (path) { var option = $('<option>' + path + '</option>'); select.append(option); }); select.val(defaultVal); select.change(SetVersionedGroup); select.insertBefore('#input_username'); } return this; } }); new DiscoveryUrlSelector( { el: $('#api_selector'), name: 'Group', rootUrl: swashbuckleConfig.rootUrl, discoveryPaths: Array.from(new Set(swashbuckleConfig.discoveryPaths.map(x => x.substring(13, x.lastIndexOf("v"))))) } ).render(); new DiscoveryUrlSelector( { el: $('#api_selector'), name: 'Version', rootUrl: swashbuckleConfig.rootUrl, discoveryPaths: Array.from(new Set(swashbuckleConfig.discoveryPaths.map(x => x.substring(x.lastIndexOf("v"), x.length)))) } ).render(); function SetVersionedGroup() { // 获取选中的分组和版本值 const selectedGroup = $('#input_Group').val(); const selectedVersion = $('#input_Version').val(); // 从配置的所有discovery路径中匹配对应的完整路径 const targetDiscoveryPath = swashbuckleConfig.discoveryPaths.find(path => path.includes(selectedGroup) && path.includes(selectedVersion) ); if (targetDiscoveryPath) { // 拼接完整的文档API地址 const fullDocUrl = swashbuckleConfig.rootUrl + targetDiscoveryPath; // 根据SwaggerUI版本更新文档源并重新加载 if (window.swaggerUi) { // 适配旧版Swashbuckle集成的SwaggerUI swaggerUi.url = fullDocUrl; swaggerUi.load(); } else if (window.ui) { // 适配新版Swashbuckle(比如Swashbuckle.AspNetCore)的SwaggerUI实例 ui.specUrl = fullDocUrl; ui.loadSpec(); } } } })();
逻辑说明
- 获取选中值:通过jQuery选择器获取两个下拉框的选中内容,对应你创建的
input_Group和input_Version控件。 - 匹配完整路径:从
swashbuckleConfig.discoveryPaths数组中筛选出同时包含选中分组和版本的路径,确保找到的是对应分组+版本的Swagger文档地址。 - 更新并加载文档:
- 旧版Swashbuckle(比如.NET Framework中的版本)通常会暴露
window.swaggerUi实例,直接修改其url属性后调用load()即可刷新文档。 - 新版Swashbuckle.AspNetCore集成的SwaggerUI则使用
window.ui实例,修改specUrl后调用loadSpec()完成刷新。
- 旧版Swashbuckle(比如.NET Framework中的版本)通常会暴露
这样修改后,当你切换分组或版本下拉框时,SwaggerUI就会自动加载对应的API文档了。
内容的提问来源于stack exchange,提问作者DavidWaldo
相关产品推荐
相关产品推荐

