ASP.NET Core 6.0 Web API中如何将Schema嵌入Swagger端点区域
如何在Swashbuckle.AspNetCore 6.5的Swagger页面中将Schema嵌入端点区域
可以通过自定义Swagger UI的样式和脚本实现这个需求,具体步骤如下:
添加自定义静态资源
在项目的wwwroot目录下创建swagger-custom文件夹,分别新建custom.css和custom.js文件。配置Swagger中间件加载自定义资源
在Program.cs里修改Swagger的配置,添加对自定义CSS和JS的引用:
app.UseSwaggerUI(options => { options.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); // 加载自定义样式 options.InjectStylesheet("/swagger-custom/custom.css"); // 加载自定义脚本 options.InjectJavascript("/swagger-custom/custom.js"); });
- 编写自定义CSS调整布局
在custom.css中添加样式,隐藏原有的顶部Schema区域,并调整端点区域样式以容纳嵌入的Schema:
/* 隐藏顶部独立的Schema区域 */ .models { display: none !important; } /* 调整端点详情区域的底部内边距,预留Schema空间 */ .opblock-body { padding-bottom: 20px; } /* 自定义嵌入Schema的容器样式 */ .embedded-schema { margin-top: 15px; padding: 10px; border: 1px solid #ddd; border-radius: 4px; }
- 编写JavaScript实现Schema嵌入逻辑
在custom.js中编写脚本,自动将端点关联的Schema内容移动到对应端点的详情区域内:
window.addEventListener('load', function() { // 获取所有端点模块 const opblocks = document.querySelectorAll('.opblock'); opblocks.forEach(opblock => { const schemaNames = []; // 提取请求体关联的Schema名称 const requestBodySchema = opblock.querySelector('.request-body .schema-ref'); if (requestBodySchema) { schemaNames.push(requestBodySchema.textContent.trim().replace('#/components/schemas/', '')); } // 提取响应关联的Schema名称 const responseSchemas = opblock.querySelectorAll('.response .schema-ref'); responseSchemas.forEach(ref => { const name = ref.textContent.trim().replace('#/components/schemas/', ''); if (!schemaNames.includes(name)) { schemaNames.push(name); } }); // 创建嵌入Schema的容器 const embeddedSchemaContainer = document.createElement('div'); embeddedSchemaContainer.className = 'embedded-schema'; embeddedSchemaContainer.innerHTML = '<h4>关联Schema</h4>'; // 复制对应Schema到容器中 schemaNames.forEach(name => { const schemaElement = document.querySelector(`.models .model[data-model-name="${name}"]`); if (schemaElement) { const clonedSchema = schemaElement.cloneNode(true); embeddedSchemaContainer.appendChild(clonedSchema); } }); // 将容器添加到端点详情区域 const opblockBody = opblock.querySelector('.opblock-body'); if (opblockBody && embeddedSchemaContainer.children.length > 1) { opblockBody.appendChild(embeddedSchemaContainer); } }); });
说明:
- 脚本会自动识别每个端点关联的请求、响应Schema,将对应的Schema内容复制到该端点的详情区域下方。
- 如果需要更精准的控制(比如只显示响应Schema),可以修改JavaScript中的选择器和逻辑。
- 测试时要确保静态资源能正常加载,若项目未启用静态文件中间件,需在
Program.cs中添加app.UseStaticFiles();。
内容的提问来源于stack exchange,提问作者Cust_1
相关产品推荐
相关产品推荐

