c# - ASP .Core MVC 配置应用程序根 url
问题描述
我有两个托管在同一个 url 下的 ASP .Core MVC 应用程序。
我已经设法将它们与 Nginx 分开,以便某个路径进入app-2
,而其余路径进入app-1
:
http://host
-> app-1
http://host/setup
->app-2
当用户连接到时,我的问题就出现了app-2
,因为应用程序仍然认为它是 app-root is http://host
。
这会导致客户端在下载样式表时遇到 404,因为它app-2.css
存在于http://host/setup/css
但应用程序在http://host/css
.
.cshtml
文件中的“include”行app-2
如下所示:
<link rel="stylesheet" type="text/css" href="@Url.Content("~/css/app-2.css")" asp-append-version="true" />
是否有某种“覆盖”或告诉app-2
应该~
引用<host>/setup/css/
而不是的方式<host>/css/
?
我真的不想硬编码它,以防网址在某个时候发生变化。
解决方案
经过数小时的搜索,我发现无法更改整个网络服务器的应用程序根目录。
我最终做的是创建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" />
推荐阅读
- python - Opencv/Python 可执行文件创建问题
- javascript - 我们是否需要在生产结束时捆绑我们的 js 文件
- java - 三个文件中的匹配编号未显示
- c++ - 为什么我使用 fstream 的输出不好?
- ruby-on-rails - Rails:如何检查用户是否存在于控制器中,如果不重定向到其他站点
- java - 与 Spring-Boot 同时提供 JSON 响应和下载文件
- swift - 在选项卡控制器中禁用除主页之外的所有按钮
- ios - 从服务器加载图像到标签栏项目
- javascript - 单击组件时onClick未触发
- java - 将驱动程序对象分配给“new AndroidDriver”后如何解决此错误
(url,caps)”来自线程中的多个实例?