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

时间:2016-04-27 17:15:48

标签: asp.net-mvc asp.net-mvc-routing asp.net-mvc-5

我尝试从函数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);
    }

3 个答案:

答案 0 :(得分:5)

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运行时执行它!

答案 1 :(得分:2)

从响应中重定向:

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

答案 2 :(得分:0)

我尝试写下并成功:

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