Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In ASP MVC3, how can execute a controller and action using a uri?

How can I, when executing a controller action, take a Uri (not the one requested) and invoke the action from the controller that would have been executed had that Uri been the one that was called? I can't simply redirect to that action as I need it to happen in the same request context.

like image 896
mcintyre321 Avatar asked Dec 06 '22 22:12

mcintyre321


2 Answers

Assuming you have access to the HttpContext (and I suppose you do since you are asking) you could:

var routeData = new RouteData();
// controller and action are compulsory
routeData.Values["action"] = "index";
routeData.Values["controller"] = "foo";
// some additional route parameter
routeData.Values["foo"] = "bar";
IController fooController = new FooController();
var rc = new RequestContext(new HttpContextWrapper(HttpContext), routeData);
fooController.Execute(rc);

Personally I use this approach for handling errors inside my application. I put this in Application_Error and execute an error controller for custom error pages staying in the context of the initial HTTP request. You could also place complex objects inside the routeData hash and you will get those complex objects back as action parameters. I use this to pass the actual exception that occurred to the error controller action.


UPDATE:

In order to parse an URL to its route data tokens taking into account current routes you could:

var request = new HttpRequest(null, "http://foo.com/Home/Index", "id=1");
var response = new HttpResponse(new StringWriter());
var httpContext = new HttpContext(request, response);
var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));
var values = routeData.Values;
var action = values["action"];
var controller = values["controller"];
like image 88
Darin Dimitrov Avatar answered May 25 '23 10:05

Darin Dimitrov


For the correct answer, I'd prefer do something like this to let MVC handle creating controllers rather than creating myself.

var routeData = new RouteData();
// controller and action are compulsory
routeData.Values["action"] = "index";
routeData.Values["controller"] = "foo";
IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();
var requestContext = new RequestContext(new HttpContextWrapper(yourHttpContextObject), routeData);
var controller = factory.CreateController(requestContext, "FooController");
try
{
   controller.Execute(requestContext);
}
finally
{
   factory.ReleaseController(controller);
}

This would assure you that your Foo controller is getting the same behavior as other controllers.

like image 42
erenalgan Avatar answered May 25 '23 10:05

erenalgan