I try to redirect from function BeginExecuteCore to another controller all My controller inheritance the function BeginExecuteCore and I want do some logic if something happen so redirect to "XController"
How to do it?
EDIT:
Balde: I use function BeginExecuteCore I can't use Controller.RedirectToAction
protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)
{
//logic if true Redirect to Home else .......
return base.BeginExecuteCore(callback, state);
}
The Balde's solution is working but is not optimal.
Let's take an example :
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();
}
}
If you run this project you will obviously get the Google main page. But if you look at your IDE you'll note that the code is waiting for you due to the breakpoint. Why ? Because you redirected the response but didn't stop the flow of ASP.NET MVC and so, it continues the process (by calling the action).
It's not a big issue for a small website but if you forecast to have a lot of visitors, this can become a serious performance issue : potentially thousand of requests per second that run for nothing because the response is already gone.
How can you avoid that ? I have a solution (not a pretty one but it does the job) :
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();
}
}
You store your redirect results inside a controller member and you execute it when the OnActionExecuting is running !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With