If we access the HttpContext.Current.Request object in the Application_Start event in global, such as:
protected void Application_Start () { var url=HttpContext.Current.Request.Url.ToString (); }
Just simply want to pick up the URL of the current site. Everything is fine while debugging, but when we publish the site to IIS, if IIS should be in Integrated mode, it will be an exception that will report "request is not available in this context," but not if it is in Classic mode. Dudu This article is described in detail http://www.cnblogs.com/dudu/archive/2011/10/14/Application_Start_Context_Request.html
In general, there are two ways to solve this problem:
1. Change the IIS application pool to Classic mode
2. Do not access the HttpContext.Current.Request object in Application_Start.
However, in some special cases, you can get the URL of the current site in Application_Start in Integrated mode.
Although we cannot invoke the HttpContext.Current.Request object, we can obtain deployment information for the IIS site through System.Web.Hosting.HostingEnvironment.ApplicationID.
Gets the URL of the Web site indirectly through the binding information of the site.
voidApplication_Start (Objectsender, EventArgs e) { //var url = HttpContext.Current.Request.Url.ToString (); varURL =GetUrl (); //code to run when the application startsbundleconfig.registerbundles (bundletable.bundles); Authconfig.registeropenauth (); } Private stringGetUrl () {stringPath = System.Web.Hosting.HostingEnvironment.ApplicationID;//value similar to:/lm/w3svc/3/root stringURL =string. Empty; Try { //returns the result obtained through HttpContext if HttpContext can be accessed directly returnHttpContext.Current.Request.Url.ToString (); } Catch(Exception) {}//convert path to IIS pathPath = path. Replace ("/LM",""). Replace ("/root",""); stringEntpath =string. Format ("iis://localhost{0}", path); DirectoryEntry Entry=NewDirectoryEntry (Entpath); if(Entry. Properties.contains ("ServerBindings")) { varBingdings = entry. properties["ServerBindings"]. Value.tostring ();//the results are similar to 10.188.188.13:8082://to remove the ending: No. if(Bingdings. EndsWith (":") ) {bingdings= Bingdings. Substring (0, Bingdings. Length-1); } URL="/ http"+bingdings; } returnURL; }
Of course this method only applies if we only need to know the site domain name, or we can determine the first time to visit the site's initial page.
Curve salvation: How to get the URL of a website in IIS7 Integrated mode