How do I get the complete virtual path of an ASP.N

2019-03-09 08:24发布

问题:

How do I know the the complete virtual path that my application is currently hosted? For example:

http://www.mysite.com/myApp

or

http://www.mysite.com/myApp/mySubApp

I know the application path of HttpRequest but it only returns the folder name that my application is currently hosted, but how do I get the initial part?

回答1:

The domain name part of the path is not really a property of the application itself, but depends on the requesting URL. You might be able to reach a single Web site from many different host names. To get the domain name associated with the current request, along with the virtual path of the current application, you could do:

Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath

Technically, an "application" is a virtual directory defined in IIS and Request.ApplicationPath returns exactly that. If you want to get the folder in which the current request is handled, you can do this:

VirtualPathUtility.GetDirectory(Request.Path)

ASP.NET has no idea how to distinguish your sub-application from a bigger application if it's not defined as a virtual directory in IIS. Without registering in IIS, it just sees the whole thing as a single app.



回答2:

Request.Url

it contains several points that you might consider to use, see the image below:



回答3:

In .NET 4.5

    VirtualPathUtility.ToAppRelative(path)


回答4:

The below code will solve the purpose, however you have to do a bit tuning for two types of scenarios:

  1. Hosted as separate web application.
  2. Hosted as Virtual application within a web application.

    HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + HttpRuntime.AppDomainAppVirtualPath;



回答5:

Try this (Haven't tried it)

public string GetVirtualPath(string physicalPath)
{
string rootpath = Server.MapPath("~/");
physicalPath = physicalPath.Replace(rootpath, "");
physicalPath = physicalPath.Replace("\\", "/");
return "~/" + physicalPath;
}

Link 1

Link 2