MaYaN
MaYaN

Reputation: 6986

Get The Current Application Virtual Path in ASP.Net

Inside the Application_Start of my Global.asax.cs, I am trying to get the current application path using:

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

This will return for example: http://localhost:99/MySite/

I will then use this URL and do the following:

var pageToHit = virtualPath + Pages\MyOtherPage.aspx 
var client = new WebClient();
client.DownloadData(dummyPageUrl);

All this is fine when I run the project in IIS 6 or the Visual Studio built-in web server, however things go crazy in IIS 7 as I get a "System.Web.HttpException: Request is not available in this context".

I am aware of this thread: Request is not available in this context

However, I was wondering if anyone had any idea on how to do the above without changing the project to run in classic mode.

Upvotes: 7

Views: 16598

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

You cannot access the absolute url of the current request inside Application_Start when running in integrated mode. You could access the virtual path name using HostingEnvironment.ApplicationVirtualPath but not an absolute url. Here's an article which explains a common workaround. As explained in the article you have 2 possibilities:

  1. Change your application code to not use the request context (recommended)
  2. Perform the initialization in Application_BeginRequest using a lock and a singleton to ensure that this initialization is performed only once for the entire lifetime of the AppDomain. Here's a similar thread discussing this second approach.

Upvotes: 5

Related Questions