[英]ASP .Core MVC configure application root url
I have two ASP .Core MVC applications that are hosted under the same url.我有两个 ASP .Core MVC 应用程序,它们托管在同一个 url 下。
I've managed to separate them with Nginx so that a certain path goes to app-2
, while the rest goes to app-1
:我设法用 Nginx 将它们分开,以便某个路径转到
app-2
,而其余路径转到app-1
:
http://host
-> app-1
http://host
-> app-1
http://host/setup
-> app-2
http://host/setup
-> app-2
My problem comes when the user connects to app-2
, as the application still thinks it's app-root is http://host
.当用户连接到
app-2
,我的问题就出现了,因为应用程序仍然认为它的 app-root 是http://host
。
This leads to the client encountering a 404 when for example style sheets are downloaded, since app-2.css
exists under http://host/setup/css
but the application searches in http://host/css
.这会导致客户端在下载样式表时遇到 404,因为
app-2.css
存在于http://host/setup/css
但应用程序在http://host/css
。
The "include"-lines in the .cshtml
file in app-2
look like this: app-2
.cshtml
文件中的“include”行如下所示:
<link rel="stylesheet" type="text/css" href="@Url.Content("~/css/app-2.css")" asp-append-version="true" />
Is there some way of "overriding" or telling app-2
that ~
should refer to <host>/setup/css/
instead of <host>/css/
?有什么方法可以“覆盖”或告诉
app-2
~
应该引用<host>/setup/css/
而不是<host>/css/
?
I really don't want to hardcode it in case the url changes at some point.我真的不想对其进行硬编码,以防 url 在某些时候发生变化。
After many hours of searching I found no way of altering the application root for the entire webserver.经过数小时的搜索,我发现无法更改整个网络服务器的应用程序根目录。
What I ended up doing instead was create class PathHelper
with options and added it to Startup.cs
:我最终做的是使用选项创建类
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");
});
[...]
}
I then used it in the .cshtml
files like this:然后我在
.cshtml
文件中使用它,如下所示:
@inject PathHelper helper
<link rel="stylesheet" type="text/css" href="@Url.Content(helper.Path + "css/app-2.css")" asp-append-version="true" />
I think the easiest way is to include the base
tag in pages coming from 'app-2'.我认为最简单的方法是在来自“app-2”的页面中包含
base
标签。
Try it like this:像这样尝试:
<html>
<head>
<base href="http://host/setup">
</head>
Now your relative links are sent to 'app-2'.现在您的相关链接被发送到“app-2”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.