tags:

views:

393

answers:

2

I think MvcApplication is a global singleton. I want to get the instance of MvcApplication in controller. Then I put following code in controller: MvcApplication app = HttpContext.Current.Application as MvcApplication;

it give me error: Error 2 'System.Web.HttpContextBase' does not contain a definition for 'Current' and no extension method 'Current' accepting a first argument of type 'System.Web.HttpContextBase' could be found (are you missing a using directive or an assembly reference?)

Why? How to access MvcApplication in controller?

+1  A: 

Try this:

var app = HttpContext.ApplicationInstance as MvcApplication;
eu-ge-ne
I try it in the constructor of controller like:<br/>var app = HttpContext.ApplicationInstance as MvcApplication;<br/>then I got error in the page:<br/>Server Error in '/' Application.<br/>....<br/>Line 35:var app = HttpContext.ApplicationInstance as MvcApplication;
KentZhou
You should avoid accessing controller properties such as HttpContext or ControllerContext in constructor. Try the same in Action or OnActionExecuting()
eu-ge-ne
+1  A: 

I believe the reason why the original code didn't work is because HttpContext is both a property of Controller and its own class. Within a subclass of Controller, HttpContext will resolve to the property and produce the error mentioned. To get around it, explicitly reference the HttpContext class with it's fully qualified name:

System.Web.HttpContext.Current.Application

Or, since the HttpContext property already returns the current HttpContext instance, you could use:

HttpContext.Application
Matt Hopkins