首页 > 解决方案 > 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/
我真的不想硬编码它,以防网址在某个时候发生变化。

标签: c#asp.net-coreasp.net-core-mvc

解决方案


经过数小时的搜索,我发现无法更改整个网络服务器的应用程序根目录。
我最终做的是创建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" />

推荐阅读