Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where does ASP.NET virtual path resolve the tilde "~"?

Tags:

asp.net

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?

like image 677
andres descalzo Avatar asked Dec 30 '10 14:12

andres descalzo


2 Answers

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);
}
like image 54
Aliostad Avatar answered Nov 13 '22 10:11

Aliostad


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.

like image 34
Brian Avatar answered Nov 13 '22 11:11

Brian