Getting the address of the hosting server

One of the simple problems I’ve encountered was just getting the name of the server that’s running my ASPX application, whether it be the localhost:xxxx of VS 2008’s Cassini server, localhost, or http://www.myserver.com. The following commend returns that as a string.

Html.Encode(HttpContext.Current.Request.ServerVariables[“HTTP_HOST”]

The ServerVariables NameValueCollection has a very interesting collection of information that I can see being quite useful to know about in future.

DotNetJunkies has a good tutorial on ServerVariables in ASP.Net.

Note: The command above only returns the address as a string, not the protocol. If you want to use it in an anchor tag (<a href=”someaddress”>somelink</a>) don’t forget to append the protocol (e.g. ‘http://&#8217;) to the string returned from the command or you may experience some strange behaviors.