Home
C#.ASP.NET
ServerVariables Example
Updated May 26, 2023
Dot Net Perls
ServerVariables. This returns important information from Request. This collection can be used to return an ASP.NET website's domain name programmatically.
Possible use. Often ASP.NET code is used on many different domain names. With ServerVariables, we don't need to hard code the domain name.
Example. You can get the current website's domain name using the ServerVariables collection on the Request object. The example here uses the HttpContext.Current property.
Info This is a static class, which means it can only contain static methods and fields. It cannot be instantiated with a constructor.
Here GetHode() returns the host name. The code accesses the current request and looks up the "HTTP_HOST" in ServerVariables.
using System.Web; /// <summary> /// Contains utility methods for domain names. /// </summary> public static class DomainMethods { /// <summary> /// Get the host with http as a string. /// </summary> public static string GetHost() { return "http://" + HttpContext.Current.Request.ServerVariables["HTTP_HOST"]; } }
Example 2. The code here prints the host name to the browser. Please note that localhost is the domain name when you are running locally in the development environment.
Here We see a Page that calls GetHost—the method returns a string containing "http://" and the host name.
And I have this exact code running on a deployed website. It shows the actual domain, such as "http://example.com".
using System; using System.Web.UI; public partial class _Default : Page { protected void Page_Load(object sender, EventArgs e) { base.Response.Write(DomainMethods.GetHost()); } }
ServerVariables can be useful. We obtained the domain name and host name in an ASP.NET website with ServerVariables. This can make websites easier to create and maintain.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on May 26, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen