How to check if localhost

Viewed 65176

Is there a way in c# to check if the app is running on localhost (as opposed to a production server)?

I am writing a mass mailing program that needs to use a certain mail queue is it's running on localhost.

if (Localhost)
{
Queue = QueueLocal;
}
else
{
Queue = QueueProduction;
}
11 Answers

string hostName = Request.Url.Host.ToString();

I know this is the really old thread but still, someone looking for a straight solution then you can use this:

if (HttpContext.Current.Request.Url.Host == "localhost")
{
  //your action when app is running on localhost
}

This is an alternative, more transparent, option:

public static bool IsLocal
{
    // MVC < 6
    get 
    {
        var authority = HttpContext.Request.Url.Authority.ToLower();

        return authority == "localhost" ||
               authority.StartsWith("localhost:");
    }
    // MVC 6+
    get 
    { 
        return String.Compare(HttpContext.Request.Url.Host, "localhost", 
                              StringComparison.OrdinalIgnoreCase);
    }
}

If you're not doing this in the Controller then add Current after HttpContext, as in HttpContext.Current.Request...

Also, in MVC 6, in the View, HttpContext is just Context

Related