Saeid Alizade
Saeid Alizade

Reputation: 863

Different Ways To Get The Server Name In ASP.NET

I want to log my server name in ASP.NET Application, I use multi-servers and load balancing so I need to log the server name.

But what is the difference between these ways to get the server name?

and which one is true or better to log?

any idea?

or any other ways?

System.Environment.MachineName
Server.MachineName
System.Net.Dns.GetHostName()

There is also another ways but not always return correct server name:

Request.ServerVariables["SERVER_NAME"]
System.Net.Dns.GetHostEntry(Request.ServerVariables("SERVER_NAME")).HostName
System.Net.Dns.GetHostEntry(Request.ServerVariables("LOCAL_ADDR")).HostName

Upvotes: 11

Views: 18265

Answers (2)

shreesha
shreesha

Reputation: 1881

I know this is an old question. I was searching for answer to the same issue; here is my solution.

string url = HttpContext.Current.Request.Url.ToString();
string[] tempArray = url.Split('/');
string serverName = tempArray[0] + "/" + tempArray[1] + "/" + tempArray[2] ;

This way you will get the exact server name.

Upvotes: 1

SinaX
SinaX

Reputation: 1

I always prefer simple and fail-safe solutions. I suggest to add an application setting to the application web.config and populate it with the desired name for each server manually.

<appSettings>
  <add key="ServerName" value="Server_1" />
</appSettings>

you can read this setting later:

string serverName = ConfigurationSettings.AppSettings["ServerName"];

This way you will gain full manual control on your server names.

Upvotes: -5

Related Questions