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

如何在内存中加载默认Swagger index.html并进行自定义

如何加载并自定义Swagger默认的index.html(无需替换为自定义文件)

要实现加载Swagger默认的index.html到内存并自定义内容,核心是利用SwaggerUIOptions的IndexStream属性,读取Swagger官方包内的默认资源文件,转换为字符串修改后再转回流使用。

实现步骤

  • 定位Swagger默认index.html的资源路径
  • 读取资源流并转为字符串,执行自定义修改逻辑
  • 将修改后的字符串转回流,赋值给IndexStream覆盖默认页面

修改后的完整代码

using System.IO;
using System.Text;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

internal static IApplicationBuilder UseApiDocumentationUI(this IApplicationBuilder builder, string applicationName)
{
    if (builder is null)
    {
        throw new ArgumentNullException(nameof(builder));
    }

    var configuration = builder.ApplicationServices.GetRequiredService<IConfiguration>();
    var apiVersionDescriptionProvider = builder.ApplicationServices.GetRequiredService<IApiVersionDescriptionProvider>();
    var identityOptions = new MicrosoftIdentityOptions(configuration);
  
    builder.UseMiddleware<ApiDocumentationConfigurationMiddleware>();
    builder.UseSwaggerUI(options =>
    {
        options.DocumentTitle = applicationName;
        
        // 获取Swagger官方包中的默认index.html资源流
        var defaultIndexStream = typeof(SwaggerUIOptions).Assembly.GetManifestResourceStream("Swashbuckle.AspNetCore.SwaggerUI.index.html");
        if (defaultIndexStream == null)
        {
            throw new FileNotFoundException("未找到Swagger默认的index.html资源文件");
        }

        // 将流转换为字符串,进行自定义修改
        using var reader = new StreamReader(defaultIndexStream);
        var indexHtmlContent = reader.ReadToEnd();
        
        // 示例自定义逻辑:替换页面底部内容
        indexHtmlContent = indexHtmlContent.Replace("</body>", "<p style='text-align:center; padding:10px;'>自定义底部提示</p></body>");

        // 将修改后的字符串转回流,赋值给IndexStream
        options.IndexStream = () => new MemoryStream(Encoding.UTF8.GetBytes(indexHtmlContent));

        foreach (var description in apiVersionDescriptionProvider.ApiVersionDescriptions)
        {
            options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName);
        }

        options.OAuthClientId(identityOptions.ClientId);
    });

    return builder;
}

关键说明

  • 默认index.html的资源路径为Swashbuckle.AspNetCore.SwaggerUI.index.html,对应Swashbuckle.AspNetCore.SwaggerUI程序集
  • 可通过字符串替换、正则匹配等方式对HTML内容做任意自定义调整
  • 修改完成后将字符串转为MemoryStream,赋值给IndexStream即可替换默认页面

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 14:15:37