Not able to Inject Javascript in Swagger

11.1k Views Asked by At

I get a 404 for a JavaScript file that I am trying to inject in my swagger. Following is my swagger config

var thisAssembly = typeof(SwaggerConfig).Assembly;

GlobalConfiguration.Configuration 
    .EnableSwagger(c =>
        {
            c.SingleApiVersion("v1", "A title for your API");
        })
    .EnableSwaggerUi(c =>
        {
            c.InjectJavaScript(thisAssembly,"MyApi.Api.SwaggerExtensions.inject.js");   
        });

For inject.js build action is set to embedded resource and logical path is correct as my project name is MyApi.Api and the file is in a folder within the project named SwaggerExtensions

3

There are 3 best solutions below

4
On BEST ANSWER

When using custom resources the resource name should contain the default namespace of your project as described here. In your case the configuration should be:

c.InjectJavaScript(thisAssembly, "AcctMgmt.SwaggerExtensions.inject.js")
0
On

I spent a lot of time trying to figure out that a method with the same name has a different behavior. The config in Startup.Configure expects a relative path from wwwroot:

public void Configure(IApplicationBuilder app) {
    //
    app.UseSwagger();
    app.UseSwaggerUI(c => {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "Salon API v1");
        c.InjectJavascript("/SwaggerExtension.js");
    });
}

Get started with Swashbuckle and ASP.NET Core

0
On

Had the same issue with .NET 6.

The solution was to include a wwwroot folder in the WebApi project and add all the custom files to that folder. The rest of the Swagger configuration is as simple as it gets.

Directory of custom files: wwwroot/OpenApi/CustomScript.js

Swagger configuration:

app.UseSwaggerUI(c =>
{
    c.RoutePrefix = "swagger";
    c.InjectJavascript("/OpenApi/CustomScript.js");
});

Don't forget to enable UseStaticFiles middleware.

For the Build action of these custom files it seems to work with both options: None and Embedded resource.

Hope this helps anyone having the same issue.

P.S. I know that adding a wwwroot folder seems redundant and I agree. If anyone finds a way around it, let me know.