Based on my question here
I am going to get the hostname in Application_Start
so I have done it before something like:
if(string.IsNullOrWhiteSpace(Hostname))
Hostname = Dns.GetHostName();
Based on this screenshot:
But it returns skyweb
- but I want to get RND1
.
The other solution to get hostname is HttpContext.Current.Request.Url.Host;
but as you know I don't want get in through the pages event it is better be initiated at first go...
So what is the best way to do this?
Thanks in advance.
Edit1:
If you take a look at here you will see what I am looking for which pointed in picture, meanwhile I mentioned in this screenshot again:
I can't set this in configuration, It may be set while installing process or be set by admin of server manually.
I am looking for hostname while be set in adding new website.
When we add hostname and binding the applicationHost.config
file get changed which located at C:\Windows\System32\inetsrv\config
so per site it get some change like binding
,apppool
and etc, for me I see the binding for RND1
is something like :
<site name="RND1" id="3">
<bindings>
<binding protocol="http" bindingInformation="*:80:RND1" />
<binding protocol="net.pipe" bindingInformation="RND1" />
<binding protocol="net.tcp" bindingInformation="2042:RND1" />
<binding protocol="https" bindingInformation="*:443:RND1" sslFlags="0" />
<binding protocol="net.msmq" bindingInformation="RND1" />
</bindings>
</site>
So we can get that applicationhost
file and manipulate it but with some search I crossed to this which give some helpful info to get IIS binding at run time.
with little changes of codes I implemented it like below to get hostname:
private static string GetHostname()
{
// Get the Site name
string siteName = HostingEnvironment.SiteName;
// Get the sites section from the AppPool.config
Microsoft.Web.Administration.ConfigurationSection sitesSection =
Microsoft.Web.Administration.WebConfigurationManager.GetSection(null, null,
"system.applicationHost/sites");
foreach (Microsoft.Web.Administration.ConfigurationElement site in sitesSection.GetCollection())
{
// Find the right Site
if (string.Equals((string)site["name"], siteName, StringComparison.OrdinalIgnoreCase))
{
// For each binding see if they are http based and return the port and protocol
foreach (Microsoft.Web.Administration.ConfigurationElement binding in site.GetCollection("bindings"))
{
var bindingInfo = (string)binding["bindingInformation"];
return bindingInfo.Split(':')[2];
}
}
}
return null;
}
and using it in application_start
like:
void Application_Start(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(Hostname))
Hostname = GetHostname();
}