2016-04-27 200 views
1

我尝试从功能BeginExecuteCore重定向到另一个控制器 所有我控制器继承功能BeginExecuteCore,我希望做一些逻辑,如果事情发生,所以重定向到“XController”MVC 5从BeginExecuteCore重定向到另一个控制器

如何做它?

编辑:

巴尔德: 我使用功能BeginExecuteCore我无法响应使用Controller.RedirectToAction

 protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state) 
    { 


     //logic if true Redirect to Home else ....... 


     return base.BeginExecuteCore(callback, state); 
    } 
+0

虽然您的问题缺乏细节,但您可以阅读有关Controller.RedirectToAction方法。 – Balde

回答

3

的巴尔德的解决方案工作,但不是最佳的。

让我们举个例子:

public class HomeController : Controller 
{ 
    protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state) 
    { 
     Response.Redirect("http://www.google.com"); 
     return base.BeginExecuteCore(callback, state); 
    } 

    // GET: Test 
    public ActionResult Index() 
    { 
     // Put a breakpoint under this line 
     return View(); 
    } 
} 

如果运行这个项目,你会明显得到了谷歌主页。但是如果你看看你的IDE,你会注意到由于断点,代码正在等待你。 为什么?因为你重定向了响应,但并没有停止ASP.NET MVC的流动,所以它继续这个过程(通过调用动作)。

这不是一个大问题,一个小网站,但如果你预计将有大量的游客,这可以成为一个严重性能问题:因为反应已经消失了每秒运行的请求没有任何的潜在千元。

你怎么能避免这种情况?我有一个解决方案(不是一个漂亮的一个,但它的工作):

public class HomeController : Controller 
{ 
    public ActionResult BeginExecuteCoreActionResult { get; set; } 
    protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state) 
    { 
     this.BeginExecuteCoreActionResult = this.Redirect("http://www.google.com"); 
     // or : this.BeginExecuteCoreActionResult = new RedirectResult("http://www.google.com"); 
     return base.BeginExecuteCore(callback, state); 
    } 

    protected override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     filterContext.Result = this.BeginExecuteCoreActionResult; 

     base.OnActionExecuting(filterContext); 
    } 

    // GET: Test 
    public ActionResult Index() 
    { 
     // Put a breakpoint under this line 
     return View(); 
    } 
} 

您存储控制器部件内部的重定向结果和OnActionExecuting运行时,你执行吧!

+0

机会是你会收到这种错误,因为我现在用这个解决方案 INET_E_REDIRECT_FAILED –

2

重定向:

Response.Redirect(Url.RouteUrl(new{ controller="controller", action="action"})); 
+0

惊人的工作表示感谢! :) – liran

相关问题