【发布时间】:2010-12-30 14:09:36
【问题描述】:
ASP.NET 虚拟路径在哪里解析链接中的波浪号~,例如
<link rel="stylesheet" type="text/css" href="~/Css/Site.css" />
它是重定向,还是 ASP.NET MVC 中的 RedirectToAction?
【问题讨论】:
-
你的问题没有任何意义。也许你需要重新格式化它。
标签: asp.net
ASP.NET 虚拟路径在哪里解析链接中的波浪号~,例如
<link rel="stylesheet" type="text/css" href="~/Css/Site.css" />
它是重定向,还是 ASP.NET MVC 中的 RedirectToAction?
【问题讨论】:
标签: asp.net
它从这里得到它:
VirtualPathUtility.ToAbsolute(contentPath, httpContext.Request.ApplicationPath);
这是 System.Web.Mvc DLL 中PathHelpers 类的反射器输出:
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);
}
【讨论】:
ASP.NET 包含 Web 应用程序 根运算符 (~),您可以使用 在服务器中指定路径时 控制。 ASP.NET 解决了 ~ 运算符到当前的根 应用。你可以用~ 运算符与文件夹一起使用 指定一个基于 当前根目录。
基本上,波浪号的目的是即使您将网站部署到不同的地方,您也可以获得正确解析的路径。相对路径不能轻易做到这一点,因为控件可能会呈现在您网站的不同文件夹中。绝对路径无法做到这一点,因为您的网站可能会部署到不同的位置 - 如果没有其他问题,本地测试部署与发布部署到实时服务器就是这种情况。
Server.MapPath 可以用于类似的原因。
【讨论】:
ASP.Net 在每个runat=server 控件中将波浪号(~) 与应用程序的根目录进行转换。它等同于 HttpRuntime.AppDomainAppVirtualPath 属性。
【讨论】: