C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
This often involves the ASP.NET development server, or any local IIS server. We use a quick hack to detect this condition. We see one way to detect localhost as the server on your computer.
Example. Local development servers are identified as "http://localhost:" in their address. The method here simply checks for that string at the start of the URL. This is effective in my testing, and for non-critical purposes it may be sufficient.
And: Only use this when the site is in development staging and not open to attack vectors. Here's how it can be implemented.
Code that detects local site: C# using System; using System.Web; /// <summary> /// Utility functions for ASP.NET /// </summary> public static class Util { /// <summary> /// Whether request is local. /// </summary> public static bool IsLocal { get; set; } /// <summary> /// Initialize static properties. /// </summary> static Util() { IsLocal = HttpContext.Current.Request.Url.AbsoluteUri. StartsWith("http://localhost:"); } }
First create a new class in App_Code. This new class will be a static class that is available to all parts of your application. If you have a namespace, you can use that for the class.
Static ClassNamespace Examples
Next: Add System.Web—the method uses HttpContext, which is located in System.Web.
We can use the static property from any page in your ASP.NET project in the code-behind. Here is a warning for users of this code. It may have the potential to create back doors in your project, so only use it when developing.
Code that uses IsLocal property: C# protected void Page_Load(object sender, EventArgs e) { if (SiteGlobal.IsLocal) { HttpRuntime.UnloadAppDomain(); // Do something when local. } }
Summary. We saw a way you can determine if your ASP.NET website is running on the local server. You can test parts of the AbsoluteUri for convenient ways to detect the location of your site.
Tip: Use the IsLocal property to perform maintenance tasks for development, like restarting your app or running debug methods.