【问题标题】:Using Custom Index in Swagger for .NET Core 3.1在 Swagger 中为 .NET Core 3.1 使用自定义索引
【发布时间】:2020-12-13 02:50:33
【问题描述】:

通过网络搜索,我发现我可以大摇大摆地替换 index.html 文件。我遵循大多数人所说的,我可以用自定义文件替换索引文件。只需在项目中的某个位置放置一个 index.html,将其标记为嵌入资源,然后在 Startup 类的 Configure 函数中添加几行。

然后我从 git 项目(https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/master/src/Swashbuckle.AspNetCore.SwaggerUI/index.html)复制索引文件来修改它。

我的自定义索引放置在名为 Swagger 的文件夹下,并且加载良好。但是,一旦我重新加载页面,我就会得到一个异常:“ArgumentException: Stream was not readable.”。

我的配置选项如下所示:

string path = GetType().Namespace + ".Swagger.index.html";
var resource = GetType().Assembly.GetManifestResourceStream(path);

app.UseSwagger(config => { config.RouteTemplate = $"{doc_path}/{{documentName}}/{doc_file}"; });
app.UseSwaggerUI(config =>
{
    config.RoutePrefix = doc_path;
    config.SwaggerEndpoint($"{doc_vers}/{doc_file}", "Rest API Doc");
    config.InjectStylesheet($"style.css");
    config.IndexStream = () => resource);
});

我也尝试将 index.html 放在 wwwroot 文件夹下,它再次加载,但它变得更糟。网站仅显示 %(HeadContent)、%(DocumentTitle) 的标题和 javascript 控制台中的一些错误。

【问题讨论】:

    标签: .net-core swagger swagger-ui swashbuckle


    【解决方案1】:

    问题在于从 IndexStream 的 lambda 表达式创建资源路径字符串。这完全是关于 .net 核心如何处理不同的 api 调用以及它如何为每个调用构造对象。

    我必须替换这行:

    string path = GetType().Namespace + ".Swagger.index.html";
    var resource = GetType().Assembly.GetManifestResourceStream(path);
    
    app.UseSwaggerUI(config =>
    {
        -- some code here
        config.IndexStream = () => resource);
    });
    

    通过这个:

    app.UseSwaggerUI(config =>
    {
        -- some code here
        config.IndexStream = () => GetType().Assembly.GetManifestResourceStream
        (
                GetType().Namespace + ".Swagger.index.html")
        );
    });
    

    关于将index.html放在wwwroot文件夹下,swagger好像是给文件替换了一些文本,如果索引文件是使用IndexStream函数引用的note就不行了。

    【讨论】:

    • 您在浏览器中使用什么 URL 来访问 index.html?你也可以发一下吗?
    猜你喜欢
    • 2021-03-01
    • 2021-05-02
    • 1970-01-01
    • 2022-06-30
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多