Where does ASP.NET virtual path resolve the tilde ~
in the links, for example
<link rel="stylesheet" type="text/css" href="~/Css/Site.css" />
Does it redirect, or RedirectToAction
in ASP.NET MVC?
It gets it from here:
VirtualPathUtility.ToAbsolute(contentPath, httpContext.Request.ApplicationPath);
Here is the reflector output for PathHelpers
class in System.Web.Mvc DLL:
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);
}
See MSDN:Web Project Paths
ASP.NET includes the Web application root operator (~), which you can use when specifying a path in server controls. ASP.NET resolves the ~ operator to the root of the current application. You can use the ~ operator in conjunction with folders to specify a path that is based on the current root.
Basically, the purpose of the tilde is so that you can have a path that resolves properly even if you deploy your website to different places. Relative paths cannot accomplish this easily because controls may be rendered in different folders within your website. Absolute paths cannot accomplish this because your website may be deployed to different locations -- if nothing else, this is the case for test deployments made locally vs release deployments to the live server.
Server.MapPath
can be used for similar reasons.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With