如何在其标记内将较小的自定义插入 Swagger UI?

How to insert minor customization into Swagger UI inside its markup?

我有一个使用 Swashbuckle(Swashbuckle.AspNetCore.SwaggerGen 3.0.0 和 Swashbuckle.AspNetCore.SwaggerUi 3.0.0)记录的 .NET Core 项目。我的目标是在带有 class title 的 DIV 正下方添加自定义标签(即在服务名称下方但端点上方)。

当我调查 Swagger UI 标记时,我看到有一个 DIV 和 class swagger-ui 并且我我想把我的东西放进去,可以这么说。我今天的设置是一个名为 donkey.html 的文件,当我访问 Swagger UI 的 URL 时呈现如下。

...
<body>
  <div id="swagger-ui"></div>
  <div id="api_info"></div>
  <!-- ... -->
  <script src="./swagger-ui-bundle.js"></script>
  <script src="./swagger-ui-standalone-preset.js"></script>
  <script type="text/javascript">
    (function () { ... })();
  </script>
</body>
</html>

我已经在谷歌上搜索了几个小时,并阅读了很多关于 OpenAPI 和 YAML 的内容。然而,我得到的印象是它需要 Swagger UI 项目的整个 rebuild,我的目标是目前更简单的任务。

有没有办法让 DIV 调用 api_info 使其呈现为 swagger_ui 的一部分 没有重新生成整个 Swagger UI 项目?

我尝试扩充基本布局,如图所示 here 但结果很糟糕,结果比我的目标要复杂一些。也许这是创建模块的唯一可行方法,在这种情况下我会考虑它,但这是本例中的最后资源。

Swagger UI 3.x 具有允许您添加或修改 UI 元素的插件系统。可以在以下位置找到有关插件的一些文档:
Plugins
What's the intended way of customizing SwaggerUI 3.x?

无需重新编译Swagger UI即可使用插件,实际上您可以直接在index.html页面中定义插件。要添加或更改 UI 元素,您需要一个使用 wrapComponentsReact.createElement to build the desired DOM structure. (See also React Without JSX 的插件。)

要使自定义插件生效,必须将它们添加到 SwaggerUIBundle 构造函数中的 plugins 列表中。

例子

这是一个示例插件,它在 API 标题的上方和下方添加了自定义 <h3> headers:

// index.html

<script>
window.onload = function() {

  // Custom plugin that adds extra stuff
  const MyCustomPlugin = function() {
    return {
      wrapComponents: {
        // add text above InfoContainer - same effect as above title
        InfoContainer: (Original, { React }) => (props) => {
          return React.createElement("div", null,
            React.createElement("h3", null, "I'm above the InfoContainer"),
            React.createElement(Original, props)
          )
        },

        // and/or add text above API description
        InfoUrl: (Original, { React }) => (props) => {
          return React.createElement("div", null,
            React.createElement(Original, props),
            React.createElement("h3", null, "I'm above the API description")
          )
        }
      }
    }
  }


  const ui = SwaggerUIBundle({
    url: "http://petstore.swagger.io/v2/swagger.json",
    dom_id: '#swagger-ui',
    ...
    plugins: [
      MyCustomPlugin,       // <------ add your custom plugin here
      SwaggerUIBundle.plugins.DownloadUrl
    ],
    ...

结果如下所示: