如何配置Swashbuckle隐藏Curl命令与Responses表格?
在ASP.NET Core 7中配置Swashbuckle UI隐藏指定元素
1. 隐藏Curl命令
Swashbuckle UI支持通过注入自定义JavaScript来修改界面,这是官方提供的开箱即用扩展方式,不需要第三方工具。
首先在Swagger UI配置中添加脚本注入:
builder.Services.AddSwaggerGen(); app.UseSwaggerUI(options => { options.InjectJavascript("/swagger-custom.js"); });
然后在项目的wwwroot目录下创建swagger-custom.js文件,写入以下代码:
document.addEventListener('DOMContentLoaded', function() { // 监听DOM变化,确保动态渲染的元素也能被隐藏 const observer = new MutationObserver((mutations) => { mutations.forEach(() => { document.querySelectorAll('.curl-command').forEach(el => el.style.display = 'none'); }); }); observer.observe(document.body, { childList: true, subtree: true }); });
2. 隐藏Responses表格
同样通过自定义脚本实现,在上述swagger-custom.js中补充代码即可:
// 在之前的observer回调中添加处理Responses的逻辑 document.addEventListener('DOMContentLoaded', function() { const observer = new MutationObserver((mutations) => { mutations.forEach(() => { // 隐藏Curl命令 document.querySelectorAll('.curl-command').forEach(el => el.style.display = 'none'); // 隐藏Responses表格 document.querySelectorAll('.responses-wrapper').forEach(el => el.style.display = 'none'); }); }); observer.observe(document.body, { childList: true, subtree: true }); });
备选方案:自定义Swagger UI模板
如果需要更彻底的控制,可以替换Swagger UI的默认HTML模板:
- 从Swashbuckle的源码中复制默认的
index.html模板到项目中 - 修改模板,移除对应Curl命令和Responses表格的渲染代码
- 在配置中指定自定义模板:
app.UseSwaggerUI(options => { options.IndexStream = () => GetType().Assembly.GetManifestResourceStream("YourProject.Swagger.index.html"); });
内容的提问来源于stack exchange,提问作者THX-1138
相关产品推荐
相关产品推荐

