Access current domain name on Application_Start

TheAlbear picture TheAlbear · Oct 4, 2011 · Viewed 9.2k times · Source

Normally to access the current domain name e.g where the site is hosted I do something like

string rURL = HttpContext.Current.Request.Url.ToString().ToLower();

But HttpContext is not avaible on Application_Start only from Application_BeginRequest.

Any ideas?

Answer

Jeremy McGee picture Jeremy McGee · Oct 4, 2011

A single IIS application can be bound to many different URLs. Application_Start fires before any request has been received, so the only way to find the domain name to which the site is bound is to query IIS.

Even then you may not be able to get an answer - consider the situation where an application is bound to a wildcard / default hostname.

A better approach may be to look at Application_AuthenticateRequest. This fires before Application_BeginRequest and does give you a full HttpContext.Current.Request object.