ASP.NET ServerVariables ExampleUse the ServerVariables collection to get information about the server.
dot net perls
ServerVariables returns important information from Request. This collection can be used to return an ASP.NET website's domain name programmatically. Often ASP.NET code is used on many different domain names.
And With ServerVariables, we don't need to hard code the domain name. This makes programs easier to maintain.
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, which means you can easily use it from a C# class.
Static This is a static class, which means it can only contain static methods and fields. It cannot be instantiated with a constructor.
GetHost This returns the host name. The code accesses the current request and looks up the "HTTP_HOST" in ServerVariables.
Example 2. Next we use the method. 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.
Example This is a web forms page that calls the static method we defined earlier. It returns the 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".
Method that uses ServerVariables: C#
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"]; } }
Summary. ServerVariables can be useful. We obtained the domain name and host name in an ASP.NET website with ServerVariables. You do not need to store the domain name in a configuration file such as Web.config.
Tip I recommend using this code and caching the result in a static field for best performance.
Webpage file that prints method result
using System; using System.Web.UI; public partial class _Default : Page { protected void Page_Load(object sender, EventArgs e) { base.Response.Write(DomainMethods.GetHost()); } }
© 2007-2021 sam allen. see site info on the changelog