Lir*_*ran 2 asp.net-mvc asp.net-mvc-routing asp.net-mvc-5
我尝试从函数BeginExecuteCore重定向到另一个控制器所有我的控制器继承函数BeginExecuteCore我想做一些逻辑,如果发生的事情,所以重定向到"XController"
怎么做?
编辑:
Balde:我使用函数BeginExecuteCore我不能使用Controller.RedirectToAction
protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)
{
//logic if true Redirect to Home else .......
return base.BeginExecuteCore(callback, state);
}
Run Code Online (Sandbox Code Playgroud)
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();
}
}
Run Code Online (Sandbox Code Playgroud)
如果您运行此项目,您显然会获得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();
}
}
Run Code Online (Sandbox Code Playgroud)
您将重定向结果存储在控制器成员中,并在OnActionExecuting运行时执行它!
| 归档时间: |
|
| 查看次数: |
2757 次 |
| 最近记录: |