Can anybody tell me if there is a way for me to get the domain name of my site in the Application_Start event in the global.asax?
Normally I’d just get it from Context.Request.ServerVariables[“SERVER_NAME”], but this is not available. I’d ideally also like to get the URL from the request that kicked off the application.
Hmm – from answers below, it would seem that being on IIS7 makes a difference here. This is new and there are now design guidelines to try and stop you from doing it:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Edit, Based on some of your comments I did some additional research
This error is due to a design change in the IIS7 Integrated pipeline that makes the request context unavailable in Application_Start event. When using the Classic mode (the only mode when running on previous versions of IIS), the request context used to be available, even though the Application_Start event has always been intended as a global and request-agnostic event in the application lifetime. Despite this, because ASP.NET applications were always started by the first request to the app, it used to be possible to get to the request context through the static HttpContext.Current field.
So you have two options
- Change your application code to not use the request context (recommended).
- Move the application to Classic mode (NOT recommended).
Your web-application could run under multiple different domains. Since there is no current request in the
Application_Start event, you cannot know under which domain the application will be called.
You could however find out the machine-name using
I’m guessing you are on IIS 7? Because the HttpContext is available there on IIS 6.0.
Can you consider filling that information later on? The first call to
Application_BeginRequest for example?
In VB.NET, in Global.asax, I use the following:
It corresponds to the application name in IIS.
UPDATE: It seems the method “GetSiteName” is not intended to be called directly and it doesn’t work anymore for me in Visual Studio 2015 (or maybe it is because the framework version change I made). I fixed it by replacing it by:
Do you have access to the Request object at all? If so i think you could use
It will return the dns host name which is what you are looking for.
Have you tried: –