views:

191

answers:

1

We have a pluggable framework that returns ActionResult objects that render things to a browser. One late breaking requirement is that our plugins should be callable from a regular ASP.NET Web Forms application.

So far I have come up with this, which works for very basic ActionResults:

public class ActionResultTranslator {

    HttpContextBase _context;

    public ActionResultTranslator(HttpContextBase context ) {

        _context = context;
    }

    public void Execute(ActionResult actionResult) {

        ControllerContext fakeContext = new ControllerContext();
        fakeContext.HttpContext = _context;            

        actionResult.ExecuteResult(fakeContext);        
    }
}

You would call the above from a web form with:

protected void Page_Load(object sender, EventArgs e) {
   HttpContextWrapper contextWrapper = new HttpContextWrapper(this.Context);
   var translator = new ActionResultTranslator(contextWrapper);
   translator.Execute(new RedirectResult("http://google.com"));     
}

What else do I need to do to hook everything up? For example, what if I wanted to return a ViewResult?

+1  A: 

There aren't too many properties to fake on ControllerContext.

  • HttpContext - You've got this covered
  • Controller - As far as I can tell, no standard ActionResults care if this is left null
  • RequestContext - Will be populated automatically if left null
  • RouteData - Will be populated with an empty collection if left null.

So you're just left to worry that the ActionResult could depend on arbitrary keys being present in RouteData. A ViewResult should be happy as long as you populate action and controller so that it knows where to look for the view file. If you alter your code to provide a RouteData with those values, you should be OK.

stevemegson
What if I don't have an "action" and "controller" to provide? If my plugin returns a ViewResult, can I somehow mock the MVC pipeline so I can find the View and render the result so it can be streamed to the browser? Or can I just add a "dummy" controller class and a View folder in my Web Forms project?
The `controller` and `action` values are just strings telling the view engine where to look, so they don't have to refer to a real controller class or action method. In practice they're just the folder and filename of the .aspx that you want to render and as long as you have a `/Views/controller/action.aspx` file in your project, you should be fine.
stevemegson