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

别说谁变了你拦得住时间么 提交于 2019-12-23 01:11:11

问题


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

回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/40936661/asp-net-core-swagger-uses-incorrect-json-url-when-web-application-is-hosted-in-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!