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

前端 未结 3 1433
耶瑟儿~
耶瑟儿~ 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 09:18

    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"];
    

提交回复
热议问题