Access the current domain name on Application_Start

Usually, to access the current domain name, for example, where the site is located, I do something like

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

But the HttpContext not available on Application_Start only from Application_BeginRequest .

Any ideas?

+6
source share
4 answers

Try Dns.GetHostName() .

You can use this in Gloabl.asax.cs, whether within Application_Start () or not.

 var hostName = Dns.GetHostName(); 

Tested in Asp.net 4.5 MVC.

+6
source

A single IIS application can be bound to many URLs. Application_Start triggered before any request is received, so the only way to find the domain name to which the site is linked is through an IIS request.

Even then you won’t be able to get an answer - consider a situation where the application is associated with a default wildcard / name.

A better approach might be to look at Application_AuthenticateRequest . This fires before Application_BeginRequest and gives you the full HttpContext.Current.Request object.

+7
source

The IIS application does not know which domain it accessed (see the bindings) when the application started.

+3
source

One way to achieve this is a little trickster and contains warnings, but for using System.Web.Hosting.HostingEnvironment.SiteName .

p>

So it will look like this:

 string rURL = System.Web.Hosting.HostingEnvironment.SiteName; 

And now for these caveats:

  • This is the site name in IIS.
  • This means that your site name may be a non-URI (for example, my excellent site).
  • If you have multiple domains sharing the same site, they will be the same for each.

For my purposes - setting up logging on servers where I had several sites in IIS pointing to the same physical folder - the above solution was probably the simplest and easiest. I do not necessarily say this is the β€œright” answer, but it should be considered as an alternative.

+1
source

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


All Articles