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

Where does ASP.NET virtual path resolve the tilde ~ in the links, for example

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

Does it redirect, or RedirectToAction in ASP.NET MVC?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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);
}

Method 2

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.

Method 3

ASP.Net translates the tilde(~) with the application’s root directory in every runat=server control. It is the equivalent for the HttpRuntime.AppDomainAppVirtualPath Property.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x