views:

5265

answers:

6

This may not be the correct way to use controllers, but I did notice this problem and hadn't figured out a way to correct it.

public JsonResult SomeControllerAction() {

    //The current method has the HttpContext just fine
    bool currentIsNotNull = (this.HttpContext == null); //which is false    

    //creating a new instance of another controller
    SomeOtherController controller = new SomeOtherController();
    bool isNull = (controller.HttpContext == null); // which is true

    //The actual HttpContext is fine in both
    bool notNull = (System.Web.HttpContext.Current == null); // which is false        

}

I've noticed that the HttpContext on a Controller isn't the "actual" HttpContext that you would find in System.Web.HttpContext.Current.

Is there some way to manually populate the HttpContextBase on a Controller? Or a better way to create an instance of a Controller?

A: 

Is it that you want to use some functionality from the controller? Or have the controller perform an action?

If it's the former, maybe that's some code that should be split out into another class. If it's the latter, you can do this to simply have that controller do a specific action:


return RedirectToAction("SomeAction", "SomeOtherController", new {param1 = "Something" });

mmacaulay
A: 

I'm still learning what the right way to use MVC, but it more or less i'm returning a standard JSON result from all of my actions (Json at least).

In this instance I'd like to reuse this command since I already do all the validation in the method.

I've written a routine to check for values in the JsonResults (since I know what to expect)

SomeController controller = new SomeController();
JsonResult result = controller.CreateNewDevice("The device","some data");

//then check for the result    
bool? success = this.GetJsonResultValue<bool>("success",result);

But because the other routine uses the HttpContext to check for permissions, it is failing. I can go and switch all of them to the System.Web.HttpContext.Current, but I wanted to check to see if anyone knew of another way before I did it.

Hugoware
+1  A: 

The HttpContext, in the ControllerContext is null because it is not set when the controller is created. The contructor of the controller does not assign this property, so it will be null. Normally, the HttpContext is set to the HttpContext of the ControllerBuilder class. Controllers are created by the ControllerBuilder class, followed by the DefaultControllerFactory. When you want to create your own instance of a controller, you can use the ExecuteMethod of the controller with your own ControllerContext. You don't want to do that is a real application. When you get some more experience with the framework you will find the appropriate method to do want you want. When you need ControllerContext in Unit test, you can use a mocking framework to mock the ControllerContext or you can class faking it.

You can find a model of the request flow in asp.net mvc on this blog.

When your new to Asp.net mvc, it's worth the effort to download the source code and read an trace the route how a request is processed.

Paco
A: 

Are you using a controller factory? If so, how are you registering components?

I ran into this problem where I had inadvertently added an HttpContext-based dependency as a Singleton, rather than Transient in Windsor.

HttpContext was null for all but the first request. It took me a while to track down that one.

Ben Scheirman
+15  A: 

For now I'm going to do the following. This seems to be an acceptable fix...

public new HttpContextBase HttpContext {
    get {
        HttpContextWrapper context = 
            new HttpContextWrapper(System.Web.HttpContext.Current);
        return (HttpContextBase)context;                
    }
}

Where this is added to a Controller class these Controllers are inheriting from.

I'm not sure if the HttpContext being null is the desired behavior, but this will fix it in the meantime for me.

Hugoware
Thank you so much for deciphering the new way of working between the two types. I had an old class I was trying to use from an MVC controller that consumed an HttpContext object. Now I have a class that consumes an HttpContextBase object with a constructor overload that will convert between HttpContext and HttpContextBase using the HttpContextWrapper constructor you mentioned.
patridge
Yes, I too would like to say thanks for deciphering this!
Funka
+1 Great post. Been looking for this.
magnus
Spot on solution!
Ollie
+1 This is a wonderful snippet! I added to it a bit though. I wrapped your wrapper with a ContextHelper class which exposes only the properties I need out of your underlying HttpContext proeprty to allow me to then create a mock of my ContextHelper. StructureMap then allows me to swap what I need in and out. Then I created a WebSite object to act as a view API which is exposed off of all sorts of base classes for views, controllers, etc. I will have to mention this in my book (ASP.NET MVC Cookbook) if you don't mind: http://groups.google.com/group/aspnet-mvc-2-cookbook-review
Andrew Siemer
+8  A: 

Controllers are not designed to be created manually like you're doing. It sounds like what you really should be doing is putting whatever reusable logic you have into a helper class instead.

Brad Wilson
Brad, do you have somewhere that can help with understanding MVC design and best practices? MVC has been cool so far, but most examples I've found aren't very complex. They only go over the simple instances like updating a single record.
Hugoware
Brad, I have the same issue, and this is also coming from a helper class, just like you recommended. I tried the fix provided by Hugoware (below), and that fixed it. Is this the proper way to do this?
Mark Kadlec