【问题标题】:MVC 5 redirect from BeginExecuteCore to another controllerMVC 5 从 BeginExecuteCore 重定向到另一个控制器
【发布时间】:2016-08-22 03:36:31
【问题描述】:

我尝试从函数 BeginExecuteCore 重定向到另一个控制器 all 我的控制器继承了函数 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);
    }

【问题讨论】:

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

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


【解决方案1】:

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

如果你运行这个项目,你显然会得到谷歌主页。但是,如果您查看您的 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 运行时执行它!

【讨论】:

  • 您可能会收到这种错误,就像我现在使用此解决方案 INET_E_REDIRECT_FAILED 所做的那样
【解决方案2】:

从响应重定向:

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

【讨论】:

    【解决方案3】:

    我尝试写这个并成功:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多