To Overcome the error: Server cannot set status after HTTP headers have been sent in MVC try to avoid Response.Redirect() and use RedirectResult() instead.
Many time while calling a method in my MVC project, I was facing this error: Server cannot set status after HTTP headers have been sent . I was not able to encounter why this error comes, what is the reason behind it. And the main hurdle was, it runs fine most of the time so you even don't know when your server invites this error. Many time you will face this issue on production environment. There is little tips which can save your time.
The solution for this problem would be: always try to use RedirectResult() method to redirect to a url instead of Response.Redirect() as Response.Redirect() is not part of MVC pipeline.
Response.Redirect() is not part of MVC pipeline.
The possible reason behind this error can be:
You can over come this problem either setting setting BufferOutput to true before any action execute.
Response.BufferOutput = true;
Or you should use RedirectResult() method to redirect to a url instead of Response.Redirect()
In my case I was redirecting to url using Response.Redirect() method. Let see this with an example. In below code I have created a custom attribute and overriding OnActionExecuting() method of ActionFilterAttribute attribute. Below is the code.
public class CustomFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (System.Web.HttpContext.Current.User == null || !System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
{
string url = "~/Member/Login?ReturnUrl=" + HttpContext.Current.Request.Url.AbsolutePath;
HttpContext.Current.Response.Redirect(url);
}
}
}
To overcome this issue you just need to replace your redirect method. See the code below.
public class CustomFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (System.Web.HttpContext.Current.User == null || !System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
{
string url = "~/Member/Login?ReturnUrl=" + HttpContext.Current.Request.Url.AbsolutePath;
filterContext.Result = new RedirectResult(url);
}
}
}
Hope it can help you. This simple line of code can save your many hours.