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

前端 未结 3 1450
耶瑟儿~
耶瑟儿~ 2021-01-03 08:44

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 t

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-03 08:59

    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.

提交回复
热议问题