开发者

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

开发者 https://www.devze.com 2023-02-02 00:09 出处:网络
Where does ASP.NET virtual path resolve the tilde ~ in the links, for example <link rel=\"stylesheet\" type=\"text开发者_如何学编程/css\" href=\"~/Css/Site.css\" />

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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消