Jon
Jon

Reputation: 9803

ASP.NET Core Swagger uses incorrect json url when web application is hosted in a subdirectory

I followed these instructions to add swagger to my ASP.NET Core application.

It works fine when I host it as a root website but when I host the app as an alias on an existing website, say myserver.com/myapp, swagger will look for swagger.json at an incorrect URL and report: *Can't read swagger JSON from https://myserver.com/swagger/v1/swagger.json. It should instead use https://myserver.com/myapp/swagger/v1/swagger.json.

The message I get is:

Can't read swagger JSON from https://myserver.com/swagger/v1/swagger.json

How can I configure swashbuckle/swagger to use the application base path and look for the swagger.json file at the right place?

I'm hosting on IIS.

The version of swashbuckle is:

"Swashbuckle": "6.0.0-beta902"

I suspect that I'll have to add something to the app.UseSwaggerUi() in the Configure method in Startup.cs but I'm not sure what.

Startup Configure:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });

    // Enable middleware to serve generated Swagger as a JSON endpoint
    app.UseSwagger();

    // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
    app.UseSwaggerUi();
}

Upvotes: 3

Views: 3950

Answers (2)

Arno Van Jaarsveld
Arno Van Jaarsveld

Reputation: 151

You can use the ASPNETCORE_APPL_PATH environment variable to get the application basepath.

app.UseSwaggerUI(c =>
{
    string basePath = Environment.GetEnvironmentVariable("ASPNETCORE_APPL_PATH");
    if (basePath == null) basePath = "/";
    c.SwaggerEndpoint($"{basePath}swagger/v1/swagger.json", "My API");
});

Upvotes: 9

Sigurd Garshol
Sigurd Garshol

Reputation: 1544

I ended up specifying the endpoint explicitly:

app.UseSwagger();

app.UseSwaggerUi(c =>
{
    c.SwaggerEndpoint($"/swagger/v1/swagger.json", "MyAPI documentation");
    //c.SwaggerEndpoint($"/myapi/swagger/v1/swagger.json", "MyAPI documentation");
});

I've been fooling around with hosting the Web API in IIS and in IIS Express, and I end up having to swap out the endpoint depending on where I am hosting the app.

Upvotes: 0

Related Questions