MVC 5 从 BeginExecuteCore 重定向到另一个控制器

MVC 5 redirect from BeginExecuteCore to another controller

我尝试从函数 BeginExecuteCore 重定向到另一个控制器 我的所有控制器都继承了 BeginExecuteCore 函数,如果发生某些事情,我想做一些逻辑,所以重定向到 "XController"

怎么做?

编辑:

巴尔德: 我使用函数 BeginExecuteCore 我不能使用 Controller.RedirectToAction

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


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


        return base.BeginExecuteCore(callback, state);
    }

从响应重定向:

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

Balde 的解决方案有效但不是最优的。

举个例子:

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

如果您 运行 这个项目,您显然会获得 Google 主页。但是,如果您查看 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 为 运行ning !

时执行它

我尝试写这个并成功:

Response.RedirectToRoute(new { controller = "Account", action = "Login", Params= true });