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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s