How do I get the complete virtual path of an ASP.NET application - asp.net

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?

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.

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

The below code will solve the purpose, however you have to do a bit tuning for two types of scenarios:
Hosted as separate web application.
Hosted as Virtual application within a web application.
HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + HttpRuntime.AppDomainAppVirtualPath;

In .NET 4.5
VirtualPathUtility.ToAppRelative(path)

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

Url.Content("~") worked great for me and is nice and simple. I used it in the view like this:
<a href="#(Url.Content("~" + attachment))">
Here my attachment is a path like "/Content/Documents/Blah.PDF".
When my app is published to a IIS site that uses a virtual directory, Url.Content("~") resolves to just the virtual directory name like, "/app-test", for example.

Related

How to refer virtual path in asp.net?

I have created virtual directory in IIS under default web site. For example "VirtualPathTest". It refer the physical path "d:\samplelocation\VTest"
How to refer the "VirutalPathTest" in asp.net page to store file and retrieve files in that location?
The above path is not inside asp.net application.
Any one assist me to handle.
Thanks in advance.
You can achieve this by VirtualPathUtility
Ex: VirtualPathUtility.GetDirectory(Request.Path)
if you are looking to get the domain name associated with your current request, along with the virtual path of the current application, then try like this :
Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath

How to get the root url at startup in an OWIN asp.net Web API

I have found many posts very similar to this, but I didn't find any that worked for me.
I have an asp.net Web Api2 (not vnext) application, running under IIS, and using the Owin Startup class.
When installed, the root url to this will be something like
http://localhost/appvirtualdirectory
where appvirtualdirectory is the name of the virtual directory it is configured to run under in IIS.
IS there a way at startup where I have no Request property, ie in the Startup.Configure method, to get the root URL including the virtual directory being used?
Try this
HttpRuntime.AppDomainAppVirtualPath
This is valid in both global and owin startup
More details here https://msdn.microsoft.com/en-us/library/system.web.httpruntime(v=vs.110).aspx
I would use:
//you have some options but i will show you the easiest
var request = HttpContext.Current.GetOwinContext().Request;
var path = request.Scheme +
Uri.SchemeDelimiter +
request.Host +
request.PathBase;
Info about the properties I'm referencing.
https://msdn.microsoft.com/en-us/library/microsoft.owin.owinrequest(v=vs.113).aspx

Configure IIS7 to server static content through ASP.NET Runtime

I searched high an low and still cannot find a definite answer.
How do I configure IIS 7.0 or a Web Application in IIS so that ASP.NET Runtime will handle all requests -- including ones to static files like *.js, *.gif, etc?
What I'm trying to do is as follows.
We have kind of SaaSy site, which we can "brand" for every customer. "Branding" means developing a custom master page and using a bunch of *.css and other images.
Quite naturally, I'm using VirtualPathProvider, which operates like this:
public override System.Web.Hosting.VirtualFile GetFile(string virtualPath)
{
if(PhysicalFileExists(virtualPath))
{
var virtualFile = base.GetFile(virtualPath);
return virtualFile;
}
if(VirtualFileExists(virtualPath))
{
var brandedVirtualPath = GetBrandedVirtualPath(virtualPath);
var absolutePath = HttpContext.Current.Server.MapPath(brandedVirtualPath);
Trace.WriteLine(string.Format("Serving '{0}' from '{1}'",
brandedVirtualPath, absolutePath), "BrandingAwareVirtualPathProvider");
var virtualFile = new VirtualFile(brandedVirtualPath, absolutePath);
return virtualFile;
}
return null;
}
The basic idea is as follows: we have a branding folder inside our webapp, which in turn contains folders for each "brand", with "brand" being equal to host name. That is, requests to http://foo.example.com/ should use static files from branding/foo_example_com, whereas http://bar.example.com/ should use content from branding/bar_example_com.
Now what I want IIS to do is to forward all requests to static files to StaticFileHandler, which would then use this whole "infrastructure" and serve correct files. However, try as I might, I cannot configure IIS to do this.
II7 already does that if the application pool's Managed Pipeline Mode is set to Integrated which is the default. In Integrated mode, ASP.NET handles all requests including those for static objects.
If you have to leave your application pool in Classic Mode then you need to use the same techniques you would use in IIS 6 to explicitly create handlers for the various static extensions.
Additional Information Based on Comments: I think your missing piece is creating an HttpHandler to handle the other extensions (.js, .css, etc.). Without this, then ASP.NET will use the default handling for these types of files. You would create a reference to you handler in your web.config. This article is an example of creating an HttpHandler for static files.
Kudos to everyone, but the problem was in totally different space.
VirtualPathProvider cannot be used in a pre-compiled web site. I'm furious.

Getting web address for local file in ASP.Net

Is there a 'correct' way to get the proper web address for a file under an ASP.Net application? For example, I have content in '/Content/Images/Gallery/2010-01-17/small/', and I would like to iterate through all of those files, and output to the browser a link.
Now, I can do it manually by working out the path from the files FullName or I can do it from knowing the current directory, but is there a proper ASP.Net way to do it?
As you can probably tell, I'd rather use the provided method if it exists :)
Regards
Moo
You can use the method ResolveUrl() for that. If your content directory is located directly under you web app's root directory, then this should work:
// "~" results in an URL to your web app's root directory
string imageBaseUrl = this.ResolveUrl("~/content/gallery/2010-01-17/small");
Then you can append the names of the images to that base URL.
I think ResolveUrl is only part of the answer.
Unfortunately, there is not a built-in function to return a full URL to a particular resource, inclusive of hostname and protocol. Part of the reason for this is that you can access a URL any number of ways... and the server is completely agnostic of the hostname. You have to look at either the Request.Url properties to build a new URL from the user's request, or use ServerVariables.
See this question:
How to Convert "~/default.aspx" to "http://www.website.com/default.aspx" C#?

Read a web.config file in a virtual directory

I have an ASP.NET application (Root Application) that has a virtual directory set up to another ASP.NET application (Virtual Application). How can I make the Virtual Application read values from the Root Application's web.config file? I was looking at the WebConfigurationManager.OpenWebConfiguration() class, but I'm unsure how how to tell it to go up one level from the root. For example, I would tell it to go to ~/web.config to get the the Virtual Application's web.config file, but I need it to go up one more level to the Root Application's file structure. Is this even the correct approach?
Any help would be greatly appreciated!!
You can use the ExeConfigurationFileMap class with ConfigurationManager, like:
string configFile = new FileInfo(Server.MapPath("/Web.config")).Directory.Parent.FullName + "\\Web.config";
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = configFile;
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
Response.Write(config.AppSettings.Settings["Test"].Value);
IIS does have programmatic access to its configuration data (which is documented on MSDN and/or Technet). This will be the only supported route (i.e. will continue to work across IIS versions).
Otherwise you can hack a solution (both of these will require higher than usual rights for the process):
Parse the output from appcmd.exe:
E.g. here:
> C:\Windows\system32\inetsrv\appcmd.exe list vdir
VDIR "Default Web Site/" (physicalPath:E:\Dev\weblocal\XYZ)
VDIR "Default Web Site/DevRoot/TestWebClient" (physicalPath:E:\Dev\Tests\ClientSideWeb)
VDIR "Default Web Site/Home" (physicalPath:E:\Data\Homepages)
Read the configuration directly from C:\Windows\System32\inetsrv\config.
I think you will find that your desired behavior is in fact the default behavior.
web.config settings cascade down. Your app will look up to the next hierarchical web.config if it can't find the value.
This would allow you to just look up via AppSettings etc. for most cases.
I'm not sure what happens if you really need to direct access to the file as opposed to the various config api access methods.
I have a setup like this right now using IIS7 with multiple virtual apps configured.
I tried HectorMac's suggestion again and it still doesn't work for me. As a result I am going to seek an alternative to storing my value in the web.config file.

Resources