我有两个ASP . core MVC应用程序托管在同一个url下。
我已经设法将它们与Nginx分开,以便特定的路径进入app-2
,而其余的则进入app-1
:http://host
->app-1
http://host/setup
->app-2
当用户连接到app-2
时,我的问题来了,因为应用程序仍然认为它的应用程序根是http://host
.
这导致客户端遇到404时,例如样式表下载,因为app-2.css
存在于http://host/setup/css
下,但应用程序在http://host/css
中搜索。
app-2
中.cshtml
文件中的"include"行如下:
<link rel="stylesheet" type="text/css" href="@Url.Content("~/css/app-2.css")" asp-append-version="true" />
有没有办法"重写"?或者告诉app-2
,~
应该引用<host>/setup/css/
而不是<host>/css/
?
我真的不想硬编码它,以防url在某个时候发生变化。
经过几个小时的搜索,我发现没有办法改变整个web服务器的应用程序根目录。
我最终做的是创建类PathHelper
与选项,并将其添加到Startup.cs
:
class PathHelper
{
public PathHelper(IOptions<PathHelperOptions> opt)
{
Path = opt.Path;
if (Path.StartsWith('/'))
{
Path = Path[1..];
}
if (!Path.EndsWith('/'))
{
Path = Path + '/';
}
}
public string Path { get; }
}
class PathHelperOptions
{
public string Path { get; set; }
}
# Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services
.AddScoped<PathHelper>()
.Configure<PathHelperOptions>(opt =>
{
opt.Path = this.configuration.GetSection("URL_SUFFIX");
});
[...]
}
然后在.cshtml
文件中使用它,像这样:
@inject PathHelper helper
<link rel="stylesheet" type="text/css" href="@Url.Content(helper.Path + "css/app-2.css")" asp-append-version="true" />
我认为最简单的方法是在来自'app-2'的页面中包含base
标签。
试着这样写:
<html>
<head>
<base href="http://host/setup">
</head>
现在你的相对链接被发送到'app-2'。