在ASP MVC3,怎么能执行使用URI控制器和动作? [英] In ASP MVC3, how can execute a controller and action using a uri?

查看:165
本文介绍了在ASP MVC3,怎么能执行使用URI控制器和动作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何,执行控制器操作时,采取了开放的(不是那个需要)和援引,将已执行过该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.

推荐答案

假设你已经获得了HttpContext的(我想你做,因为你问)你可以:

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);

我个人使用这种方法来处理我的应用程序中的错误。我把这个的Application_Error 和执行自定义错误页停留在初始HTTP请求的上下文错误控制器。你也可以把复杂的对象的的RouteData 散里面,你会得到那些复杂的对象向后动作参数。我用这个来传递发生错误控制器动作实际的异常。

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.

更新:

为了解析一个URL,它的路由数据令牌考虑到当前的路由你可以:

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

这篇关于在ASP MVC3,怎么能执行使用URI控制器和动作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆