Reputation: 127
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:
Initialize(RequestContext requestContext)
etcEndResponse=true
on Redirect methodMVC 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!
Upvotes: 2
Views: 2419
Reputation: 17425
Response.Redirect(anyUrl)
cause 302
status code
And Html.AntiForgeryToken()
has conflict with 302
status code normally.
You can put the following code in Application_Start
:
AntiForgeryConfig.SuppressXFrameOptionsHeader = true;
Security Warning:
SuppressXFrameOptionsHeader =true
prevents your site from being loaded into an iframe.
Upvotes: 1
Reputation: 3071
I'm not familiair with the method BeginExecuteCore() as i am still working with mvc 3 and 4.
In mvc 4 i would use an action filter to check something before a page loads.
The reason why you are seeing that error is probably because you are to late redirecting the user as the page is already being loaded.
public class LogActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (condition == true)
filterContext.Response.Redirect(string.Format("https://{0}/en/en", Request.Url.Authority), true);
}
}
Take a look at: http://www.asp.net/mvc/tutorials/older-versions/controllers-and-routing/understanding-action-filters-cs
Upvotes: 0