2

In my MVC web application, I'm checking Request.IsLocal to see if the application is running on my machine--if it is, I set a Global static variable which tells the rest of my application that I am in 'Debug Mode'.

The problem is, I don't know when to do this check.

I tried to do it in the global.asax.cs file, under Application_Start(), like this:

protected void Application_Start()
{
    if (Request.IsLocal)
        isDebug = true;

    AreaRegistration.RegisterAllAreas();
    RegisterRoutes(RouteTable.Routes);
    ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
}

The trouble is, the Request object has not been initialized yet. I get a HttpException which says

The incoming request does not match any route

So, my question is when does the Request object get initialized, and is there an event of some sort that I could handle in order to run this check after the Request object is ready?

tereško
  • 58,060
  • 25
  • 98
  • 150
Slider345
  • 4,558
  • 7
  • 39
  • 47
  • 2
    does this help (purely in terms of understanding when the `Request` is created): http://blog.codeville.net/2007/11/20/aspnet-mvc-pipeline-lifecycle/ – sellmeadog Mar 07 '12 at 19:39

5 Answers5

3

Checking System.Environment.MachineName is probably a better way to do this.

Jason
  • 86,222
  • 15
  • 131
  • 146
2

Maybe use the web.config debug mode to determine this?

https://stackoverflow.com/a/542896/40822

Community
  • 1
  • 1
dotjoe
  • 26,242
  • 5
  • 63
  • 77
2

Application_Start() fires when your MVC site's app pool is spun up. It doesn't really know about the "request" object. So even though this is the correct place to set something application-wide, you won't be able to do it with Request.IsLocal. You'll have to use a different stragegy. @Jason's suggestion of using the machine name is a good option.

If you'd like to check Request.IsLocal for every request, write a handler for method for Application_BeginRequest in global.asax. See this for more info.

Evan
  • 2,113
  • 1
  • 20
  • 24
  • 1
    Jason and dotjoe provided excellent ideas, but your answer clarified for me when the request object should be accessed. – Slider345 Mar 07 '12 at 21:36
0

Check bool isLocal = HttpContext.Current.Request.IsLocal; but not in Application_Start

It may help: Global ASAX - get the server name

Community
  • 1
  • 1
Misha Ts
  • 431
  • 1
  • 4
  • 16
0

Request and HttpContext.Current are created per request (also it may look like singleton object it really is not). So if you want to set application-wide configuration - Application_Start is the right place, but you'll not have request object there (even if you would it is wrong place since requests are not necessary coming from the same machine all the time).

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179