Get 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/

Then I will 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 a project in IIS 6 or the Visual Studio Embedded Web Server, but in IIS 7 it’s all crazy as I get the request "System.Web.HttpException: Request" in this context ".

I know this topic: Request in this context is not available

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

+6
source share
1 answer

You cannot access the absolute URL of the current request inside Application_Start when working in integrated mode. You can access the name of the virtual path using HostingEnvironment.ApplicationVirtualPath , but not the absolute URL. Here's an article that explains a general workaround. As explained in the article, you have 2 options:

  • Change the application code to not use the request context (recommended)
  • Initialize in Application_BeginRequest with a lock and singleton to ensure that this initialization is performed only once for the entire AppDomain life cycle. Here a similar thread discusses this second approach.
+5
source

Source: https://habr.com/ru/post/915811/


All Articles