I want to do a simple redirect when a user first loads the website.
For that, I just access the RouteData on BeginExecuteCore()
method of BaseController and if URL does not have a specific value, then I will redirect to another https route
:
public class BaseController : Controller
{
protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)
{
// access route data
if (condition == true)
Response.Redirect(string.Format("https://{0}/en/en", Request.Url.Authority), true);
}
}
}
Some facts:
- I achieve the result I want
- I get the Exception "Server cannot append header after HTTP headers have been sent."
- I've tried several alternatives: Using other methods to do the redirect like
Initialize(RequestContext requestContext)
etc - I tried to Use parameter
EndResponse=true
on Redirect method - I tried to clear the headers before doing the redirect
- In all the previous experiments I got the same exception
- I'm using
MVC 5
My question is: How can I redirect the user to another route in the most efficient way knowing that I need to have access to RouteData and without throwing the annoying exception?
Thank you!