将Web应用程序托管在子目录中时,ASP.NET Core Swagger使用不正确的json url [英] ASP.NET Core Swagger uses incorrect json url when web application is hosted in a subdirectory
问题描述
我遵循了这些说明,以便向我的ASP.NET Core应用程序添加招摇.
I followed these instructions to add swagger to my ASP.NET Core application.
当我将其作为根网站托管时,它运行良好,但是当我在现有网站(例如myserver.com/myapp
)上作为别名托管应用程序时,swagger会在错误的URL上查找swagger.json
并报告:*可以从https://myserver.com/swagger/v1/swagger.json
读取不可靠的JSON.它应该改为使用https://myserver.com/myapp/swagger/v1/swagger.json
.
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
.
我收到的消息是:
如何配置swashbuckle/swagger使用应用程序基本路径,并在正确的位置查找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?
我在IIS上托管.
swashbuckle的版本是:
The version of swashbuckle is:
"Swashbuckle": "6.0.0-beta902"
我怀疑我必须在Startup.cs
的Configure
方法中向app.UseSwaggerUi()
添加一些内容,但是我不确定是什么.
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.
启动配置:
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();
}
推荐答案
您可以使用ASPNETCORE_APPL_PATH环境变量来获取应用程序基本路径.
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");
});
这篇关于将Web应用程序托管在子目录中时,ASP.NET Core Swagger使用不正确的json url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!