-1

How to get caller IP addres in ASP.NET MVC4 Global.asax.cs Application_Start event ? HttpContext.Current.Request object is not available there. Thread.CurrentPrincipal.Identity exists.

I want to log user name and IP address which were used to start application.

MVC4 application runs in Windows and in Mono

Andrus
  • 26,339
  • 60
  • 204
  • 378

2 Answers2

2

As you can see by the ASP.NET Lifecycle on MSDN, the Application_Start event not only happens long before the AcquireRequestState event where the request object is built, it is also done out of band with the request lifecycle altogether. In other words, Application_Start occurs only once when the application starts or when the application pool recycles, not once per request.

So, the answer to your question is simply that you can't do that (unless of course you set a static variable in the Application_Start event and use either Application_BeginRequest as in Darin's answer or an MVC filter to actually do the logging).

But MVC includes authorization filters and action filters which are meant for implementing cross-cutting concerns such as logging and/or auditing of the current user's IP address. Authorization and action filters do not run until after the request object has been created.

NightOwl888
  • 55,572
  • 24
  • 139
  • 212
0

The HttpContext is not available when the application starts. You could achieve that in the BeginRequest method in your global.asax:

private static bool initialized = false;
private static object syncRoot = new object();
protected void Application_BeginRequest()
{
    if (!initialized)
    {
        lock (syncRoot)
        {
            if (!initialized)
            {
                // do your stuff with the user IP getting from the current context
                initialized = true;
            }
        }
    }
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928