Determine if ASP.NET application is running locally

Viewed 35717

I want to know if there is a recommended way of determining if an asp application is running locally. At the moment I use the Request object and do a string search for localhost or 127.0.0.1 on the server variable but this has several limitations. The biggest one being that the Request object is not always available when I need it.

8 Answers

You can check the Request.IsLocal property

In a MVC view / ASP page / code behind class:

bool isLocal = HttpContext.Current.Request.IsLocal;

In an MVC controller :

bool isLocal = Request.IsLocal;

In response to @Meh Men's comment for other answer in this thread, who asked:

What about where Request is null. i.e: Application_start?

If you are sure your production and test or "homolog" versions of your website will all be deployed with a release version of your website, while your local environment will be built and developed in "debug" mode, you can make use of #if DEBUG sintax to write code which only should be run locally, while outside of this block, or even inside a matching #else block, you may write some other code which you want to be run only when not locally (e.g: remotely).

Here is a small sample of how I've solved this problem in a particular project I'm curreltly working on:

#if DEBUG
    // Code here will only be run locally.
#else
    // Code here will only be run "remotely".

Request is not always available in ASP.NET environment?

HttpContext and its properties Request/Response are initialized as soon as the server starts processing the page. So at any place you can execute c# code in your page life cycle you should be able to check the request url.

Related