11

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
Saeid Alizade
  • 853
  • 3
  • 9
  • 18
  • Possible duplicate of [IIS Load Balancing and ASP.Net](https://stackoverflow.com/questions/3399689/iis-load-balancing-and-asp-net) – Rob Jun 26 '19 at 11:46

2 Answers2

1

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.

robyaw
  • 2,274
  • 2
  • 22
  • 29
shreesha
  • 1,811
  • 2
  • 21
  • 30
  • Looks like that would give you **http//subdomain.host.tld[:port]** actually. E.g.: `HttpContext.Current.Request.Url.ToString().Split('/') {string[4]} [0]: "http:" [1]: "" [2]: "localhost:58905" [3]: "default.aspx"` – fortboise Jul 21 '17 at 19:12
  • And that is not the server name. It is part of the domain name, something different. – Neville Oct 04 '18 at 09:44
  • 1
    That'll get you how the client requests the URL. That would only work if the request URL is the same as the machine serving it. OP said it's under load balancing, so www.company.com would map to node004 or node002 or what have you. – Jun Sato May 01 '21 at 22:20
-5

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.

SinaX
  • 1
  • 3
  • This change to the web.config file makes this file server specific. A distinct web.config file needs to be created for each server being supported is required with this approach. This adds to the maintenance overhead that may not be wanted by those maintaining the website. – JohnH Aug 20 '19 at 16:01