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_Begin开发者_JAVA百科Request
.
Any ideas?
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.
Try Dns.GetHostName()
.
You can use this in Gloabl.asax.cs, no matter within Application_Start() or not.
var hostName = Dns.GetHostName();
tested in Asp.net 4.5 MVC.
The IIS application does not know what domain its accessed from (see bindings) at application start.
One way of achieving this is a little bit of a cheat and comes with caveats, and that's to use System.Web.Hosting.HostingEnvironment.SiteName
.
So this would look like:
string rURL = System.Web.Hosting.HostingEnvironment.SiteName;
And now for those caveats:
- This is the name of the site in IIS.
- That means your site name can be a non-URI (eg My Awesome Site).
- If you have multiple domains sharing the same site, it'll be the same for each one.
For my purposes - setting up logging on servers where I had multiple sites in IIS pointing to the same physical folder - the above solution was probably the simplest and easiest. I'm not saying it's necessarily the 'right' answer, but it should be considered as an alternative.
精彩评论