Different Ways To Get The Server Name In ASP.NET
Asked Answered
G

2

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
Greylag answered 20/2, 2014 at 6:58 Comment(1)
Possible duplicate of IIS Load Balancing and ASP.NetCauterant
T
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.

Tomasatomasina answered 11/9, 2015 at 14:23 Comment(3)
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"Mook
And that is not the server name. It is part of the domain name, something different.Palter
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.Stormi
W
-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.

Wnw answered 20/2, 2014 at 7:35 Comment(1)
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.Zoniazoning

© 2022 - 2024 — McMap. All rights reserved.