ASP.NET MVC 6 应用程序的虚拟应用程序根路径

ASP.NET MVC 6 application's virtual application root path

如何获取应用程序在服务器上的虚拟根路径?

换句话说:如何在 ASP.NET MVC 6 中执行以下操作?

HttpContext.Current.Request.ApplicationPath

您需要的可以通过 @Url.Content("~/") 实现,它将“~”映射到您的虚拟应用程序根路径。

看看 source code,似乎是使用 HttpContext.Request.PathBase 属性:

public virtual string Content(string contentPath)
{
    if (string.IsNullOrEmpty(contentPath))
    {
        return null;
    }
    else if (contentPath[0] == '~')
    {
        var segment = new PathString(contentPath.Substring(1));
        var applicationPath = HttpContext.Request.PathBase;

        return applicationPath.Add(segment).Value;
    }

    return contentPath;
}

我在 MVC Core RC2 中使用以下内容:

我使用

而不是 "~/something"

Context.Request.PathBase + "/某物"

或者更简单,只需使用 "/something",这意味着以斜线开始的路径告诉 asp 核心从根开始。