How to get the fully qualified host name + port number in Application_Start from Global.aspx?

I tried

Uri uri = HttpContext.Current.Request.Url; String host = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port; 

and it worked well on my local machine, but there is an exception when posting to IIS7 saying

 System.Web.HttpException: Request is not available in this context 

Does anyone know how to achieve this?

+47
c # url request hostname
Nov 22 2018-10-22T00:
source share
3 answers

When the web application starts, the HTTP request is not processed.

You may need to process the Application_BeginRequest (Object Sender, EventArgs e) method in which the request context is available.

Edit: Here is a sample code inspired by the Mike Volodarsky block that Michael Shimmins linked to:

  void Application_BeginRequest(Object source, EventArgs e) { HttpApplication app = (HttpApplication)source; var host = FirstRequestInitialisation.Initialise(app.Context); } static class FirstRequestInitialisation { private static string host = null; private static Object s_lock = new Object(); // Initialise only on the first request public static string Initialise(HttpContext context) { if (string.IsNullOrEmpty(host)) { lock (s_lock) { if (string.IsNullOrEmpty(host)) { var uri = context.Request.Url; host = uri.GetLeftPart(UriPartial.Authority); } } } return host; } } 
+58
Nov 22 2018-10-22T00:
source share

The accepted answer is good, but in most cases (if the first request is an HTTP request), it is better to use the Session_Start event, which is raised once for each user every 20 minutes or so (not sure how long the session is valid). Application_BeginRequest will be run on every request.

 public void Session_Start(Object source, EventArgs e) { //Request / Request.Url is available here :) } 
+7
Dec 05 '13 at
source share

Just answer it so that someone decides to really search in this thread ...

This works when starting the application in any mode ...

 typeof(HttpContext).GetField("_request", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(HttpContext.Current) 
-one
Mar 19 '15 at 20:48
source share



All Articles