ASP.NET Localhost Method

You want to check if your site is running locally on your computer, such as in the ASP.NET development server, or any local IIS server. Use a quick hack to get this working. Here we see one way to detect localhost as the server on your computer, using the C# programming language.

Browser window showing localhost

This C# tutorial uses ASP.NET and tests for localhost. It shows the Request.Url property.

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. 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:");
    }
}

Explanation. 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. Next, add System.Web. The method uses HttpContext, which is located in System.Web.

ASP.NET web programming framework

Use. Here we see that you can use the static property from any page in your ASP.NET project in the code-behind, or elsewhere in C# code. 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

Note

We saw a way you can determine if your ASP.NET website is running on the local server. Test parts of the AbsoluteUri for convenient ways to detect the location of your site. Use the IsLocal property to perform maintenance tasks for development, like restarting your app or running debug methods. There are other methods but this is convenient and useful.

ASP.NET Tutorials
.NET