【问题标题】:Where does ASP.NET virtual path resolve the tilde "~"?ASP.NET 虚拟路径在哪里解析波浪号“~”?
【发布时间】:2010-12-30 14:09:36
【问题描述】:

ASP.NET 虚拟路径在哪里解析链接中的波浪号~,例如

<link rel="stylesheet" type="text/css" href="~/Css/Site.css" />

它是重定向,还是 ASP.NET MVC 中的 RedirectToAction

【问题讨论】:

  • 你的问题没有任何意义。也许你需要重新格式化它。

标签: asp.net


【解决方案1】:

它从这里得到它:

VirtualPathUtility.ToAbsolute(contentPath, httpContext.Request.ApplicationPath);

这是 System.Web.Mvc DLLPathHelpers 类的反射器输出:

private static string GenerateClientUrlInternal(HttpContextBase httpContext, string contentPath)
{
    if (string.IsNullOrEmpty(contentPath))
    {
        return contentPath;
    }
    if (contentPath[0] == '~')
    {
        string virtualPath = VirtualPathUtility.ToAbsolute(contentPath, httpContext.Request.ApplicationPath);
        string str2 = httpContext.Response.ApplyAppPathModifier(virtualPath);
        return GenerateClientUrlInternal(httpContext, str2);
    }
    NameValueCollection serverVariables = httpContext.Request.ServerVariables;
    if ((serverVariables == null) || (serverVariables["HTTP_X_ORIGINAL_URL"] == null))
    {
        return contentPath;
    }
    string relativePath = MakeRelative(httpContext.Request.Path, contentPath);
    return MakeAbsolute(httpContext.Request.RawUrl, relativePath);
}

【讨论】:

【解决方案2】:

MSDN:Web Project Paths

ASP.NET 包含 Web 应用程序 根运算符 (~),您可以使用 在服务器中指定路径时 控制。 ASP.NET 解决了 ~ 运算符到当前的根 应用。你可以用~ 运算符与文件夹一起使用 指定一个基于 当前根目录。

基本上,波浪号的目的是即使您将网站部署到不同的地方,您也可以获得正确解析的路径。相对路径不能轻易做到这一点,因为控件可能会呈现在您网站的不同文件夹中。绝对路径无法做到这一点,因为您的网站可能会部署到不同的位置 - 如果没有其他问题,本地测试部署与发布部署到实时服务器就是这种情况。

Server.MapPath 可以用于类似的原因。

【讨论】:

    【解决方案3】:

    ASP.Net 在每个runat=server 控件中将波浪号(~) 与应用程序的根目录进行转换。它等同于 HttpRuntime.AppDomainAppVirtualPath 属性。

    【讨论】:

    • 不,不等价。 AppDomainAppVirtualPath 是“包含当前应用程序域中托管的应用程序的目录的虚拟路径”(虚拟目录)。应用程序的根目录肯定不一样,至少从 IIS7 开始。
    猜你喜欢
    • 2011-03-05
    • 2017-03-29
    • 1970-01-01
    • 2010-10-15
    • 2011-03-03
    • 2011-04-14
    • 2014-04-22
    • 1970-01-01
    • 2018-08-20
    相关资源
    最近更新 更多