You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Swashbuckle 5.6.0生成带指定参数值的Swagger UI URL?

可行方案(基于Swashbuckle 5.6.0)

Swashbuckle 5.6.0自带的Swagger UI默认不支持通过URL动态填充参数,但可以通过自定义JavaScript脚本实现需求,核心思路是解析URL中的哈希(定位API方法)和查询参数(填充值),再操作Swagger UI的DOM元素完成自动填充。

实现步骤

1. 配置Swashbuckle注入自定义脚本

在项目的SwaggerConfig.cs中,找到EnableSwaggerUi配置块,添加InjectJavaScript方法引入自定义脚本:

using System.Web.Http;
using WebActivatorEx;
using YourProjectNamespace;
using Swashbuckle.Application;

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

namespace YourProjectNamespace
{
    public class SwaggerConfig
    {
        public static void Register()
        {
            var thisAssembly = typeof(SwaggerConfig).Assembly;

            GlobalConfiguration.Configuration
                .EnableSwagger(c =>
                {
                    // 你的Swagger基础配置
                    c.SingleApiVersion("v1", "你的API名称");
                })
                .EnableSwaggerUi(c =>
                {
                    // 注入自定义脚本,替换为你的项目命名空间和脚本路径
                    c.InjectJavaScript(thisAssembly, "YourProjectNamespace.Scripts.swagger-custom.js");
                });
        }
    }
}

2. 编写自定义填充脚本

添加嵌入式资源脚本文件(如Scripts/swagger-custom.js),实现解析URL、定位API、填充参数的逻辑:

$(function() {
    // 延迟执行确保Swagger UI完全渲染
    setTimeout(function() {
        // 解析哈希路由,提取目标API/方法
        var hash = window.location.hash.substr(1);
        if (!hash.startsWith('!')) return;
        var targetPath = hash.slice(1);

        // 解析URL查询参数
        var params = new URLSearchParams(window.location.search);

        // 遍历所有API操作,匹配目标路径
        $('.operation').each(function() {
            var operationPath = $(this).find('.path a').text().trim();
            if (operationPath === targetPath) {
                // 展开目标方法的面板
                $(this).find('.heading a').click();
                
                // 填充参数到对应输入框
                params.forEach(function(value, key) {
                    var input = $(this).find(`input[name="parameters[${key}]"], select[name="parameters[${key}]"]`);
                    if (input.length > 0) {
                        input.val(value);
                        input.trigger('input'); // 触发事件让UI识别值已填充
                    }
                }.bind(this));
            }
        });
    }, 1000);
});

3. 测试目标URL

使用你预期的格式访问Swagger UI即可:

https://myserver.com/swagger/ui/index#!/MyApi/MyMethod?Param1=Foo&Param2=Bar

注意事项

  • 脚本中的DOM选择器适配Swagger UI 2.x版本(Swashbuckle 5.6.0对应版本),若你的UI结构有差异,需调整选择器(比如参数输入框的name属性)。
  • 确保URL哈希中的MyApi/MyMethod与Swagger UI显示的API路径完全一致(包括大小写、斜杠格式)。
  • 若涉及复杂参数(如对象、数组),需在脚本中额外处理序列化和填充逻辑。

内容的提问来源于stack exchange,提问作者DSoa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 13:07:28