首页 文章

当Web应用程序托管在子目录中时,ASP.NET Core Swagger使用不正确的json url

提问于
浏览
1

我按照these instructions将swagger添加到我的ASP.NET Core应用程序中 .

当我将其作为根网站托管时,它可以正常工作,但是当我将应用程序作为现有网站上的别名托管时,比如 myserver.com/myapp ,swagger会在错误的URL上查找 swagger.json 并报告:*无法从 https://myserver.com/swagger/v1/swagger.json 读取swagger JSON . 它应该使用 https://myserver.com/myapp/swagger/v1/swagger.json .

我收到的消息是:

无法从https://myserver.com/swagger/v1/swagger.json阅读swagger JSON

如何配置swashbuckle / swagger以使用应用程序基本路径并在正确的位置查找swagger.json文件?

我在IIS上托管 .

swashbuckle的版本是:

"Swashbuckle": "6.0.0-beta902"

我怀疑我必须在 Startup.csConfigure 方法中为 app.UseSwaggerUi() 添加一些内容,但我不确定是什么 .

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

2 回答

  • 0

    您可以使用ASPNETCORE_APPL_PATH环境变量来获取应用程序基路径 .

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

    我最后明确指定了 endpoints :

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

    我一直在IIS和IIS Express中托管Web API,我最终不得不换掉 endpoints ,具体取决于我托管应用程序的位置 .

相关问题