sergiommaria
sergiommaria

Reputation: 127

Error in MVC redirect: Server cannot append header after HTTP headers have been sent

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:

  1. I achieve the result I want
  2. I get the Exception "Server cannot append header after HTTP headers have been sent."
  3. I've tried several alternatives: Using other methods to do the redirect like Initialize(RequestContext requestContext) etc
  4. I tried to Use parameter EndResponse=true on Redirect method
  5. I tried to clear the headers before doing the redirect
  6. In all the previous experiments I got the same exception
  7. 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!

Upvotes: 2

Views: 2419

Answers (2)

Ramin Bateni
Ramin Bateni

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.

read more

Upvotes: 1

Jamie
Jamie

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

Related Questions