Antonio Rodríguez
Antonio Rodríguez

Reputation: 1146

Using Custom Index in Swagger for .NET Core 3.1

Searching by the web I found I can replace index.html file in swagger. I follow what most people said and I could replace the index file with a custom one. Just place a index.html somwhere in your project, mark it as embebed resource and add a few lines at Configure function in Startup class.

Then I copied the index file from git project (https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/master/src/Swashbuckle.AspNetCore.SwaggerUI/index.html) to modify it.

My custom index is placed under a folder named Swagger, and it loads well. But once I reload the page I get an exception: "ArgumentException: Stream was not readable.".

My Config options looks like this:

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);
});

I also tried to place index.html under wwwroot folder, and it loads again, but it get worse. Website only shows %(HeadContent), %(DocumentTitle) for title and a few errors at the javascript console.

Upvotes: 0

Views: 2135

Answers (1)

Antonio Rodríguez
Antonio Rodríguez

Reputation: 1146

The problem was that creating creating the resource path string out of the lambda expression for IndexStream. It's all about how .net core deal with different api calls and how it constructs objects for every call.

I have to replace this lines:

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

app.UseSwaggerUI(config =>
{
    -- some code here
    config.IndexStream = () => resource);
});

By this:

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

About placing index.html under wwwroot folder, swagger seems to replace some text for the file, and it can't do it if the index file is note referenced using the IndexStream function.

Upvotes: 1

Related Questions