解决方法
假设您可以访问HttpContext(我想您在询问时就这样做了),您可以:
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);
我个人使用这种方法来处理我的应用程序内的错误.我把它放在Application_Error中,并为停留在初始HTTP请求的上下文中的自定义错误页面执行错误控制器.您还可以在routeData哈希中放置复杂对象,然后将这些复杂对象作为操作参数返回.我使用它来传递错误控制器操作发生的实际异常.
更新:
为了解析其路线数据令牌的URL,考虑到当前路线,您可以:
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"];