2

I'm running some code in the Application_Start block within my global.asax and I'm looking for a way in which I can determine if the app is running locally so I can conditionally execute the code.

Normally I'd use something like this, but there is no httpcontext in the global.asax:

   if (Request.IsLocal == true) {
        //run the code...
   }

Is there another way in which I can determine if the app is running locally? Debug would always be set to true on the localhost, so perhaps that will give me some handle I can use?

EDIT 13th Dec

I should have clarified BeginRequest is not a suitable candidate here as the code being executed is writing a number of files to the local directory and this shouldn't be repeated on every request.

QFDev
  • 8,668
  • 14
  • 58
  • 85
  • 1
    in applicationstart you don't have a request becouse the application is starting and the meaning of local is not defined becouse an app always start and run local – giammin Dec 12 '13 at 14:58
  • 1
    if you can use `Application.BeginRequest`, that will work. – Abhitalks Dec 12 '13 at 15:00

4 Answers4

2

This one is specifically to your question about determining debug from web.config:

var configSection = ConfigurationManager.GetSection("system.web/compilation");
if (configSection.Debug) {
    // your code
}

I think you would also need to cast that appropriately. Just off the hand.

Yup. You got to cast it to System.Web.Configuration.CompilationSection.

Abhitalks
  • 27,721
  • 5
  • 58
  • 81
2

Ok decided to go with this, @abhitalks's solution also works!

   if System.Diagnostics.Debugger.IsAttached() {
        //....
   }
QFDev
  • 8,668
  • 14
  • 58
  • 85
1

This worked for me.

if (!HostingEnvironment.IsDevelopmentEnvironment)
{
      GlobalFilters.Filters.Add(new RequireHttpsAttribute());
}

To know more about how IsDevelopmentEnvironment is set, please look at the following thread.

In ASP.NET, what determines the value of HostingEnvironment.IsDevelopmentEnvironment?

Sumanth
  • 224
  • 2
  • 3
0

Easiest way to determine or categorize both is placing the required code condition to be executed locally in Application_Start, where as if it is to be executed not locally, then place it in the BeginRequest of Global.asax.

I faced this issue couple of days back and could get instant reply online.

Community
  • 1
  • 1
Shiva Saurabh
  • 1,281
  • 2
  • 25
  • 47
  • Thanks although in my case the conditional code is writing some files to the drive so it's not ideal to repeat this process on every request. That said it may work for others with more lightweight code. – QFDev Dec 12 '13 at 15:22
  • 2
    ok.another reply from your question i can guess out is trying something like Request.UserHostAddress which would usually return 127.0.0.1 usually when run locally. @QF_Developer – Shiva Saurabh Dec 12 '13 at 15:29
  • Request is not available in the context of Application_start. an HttpException is thrown – Damian Green Nov 17 '15 at 10:11