Firstly, I know there are multiple posts related to this error but nothing is helping so far.

I am getting an error "Cannot redirect after HTTP headers have been sent." in my MVC razor application when I make a call to SomeController.

How do I fix this?

[HttpPost]
public ActionResult SomeController(Object abc)
{
    Helper.somemethod("","excel");

    return View(abc);//I tried this
    return RedirectToAction("SomeController"); //I tried this also
}

public static void somemethod(string settocken, string filenames, List<Sample> samples)
{
    //Extra logic for excel that uses List<Sample> to generate excel.

    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.Cookies.Add(new HttpCookie("downloadToken", settocken));
    HttpContext.Current.Response.ContentType = "Application/x-msexcel";
    HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}.xlsx", filenames));
    using (MemoryStream ms = new MemoryStream())
    {
        try
        {
            book.Save(ms);
            HttpContext.Current.Response.BinaryWrite(ms.ToArray());
        }
        catch
        {

        }
        finally
        {

        }

        HttpContext.Current.Response.End();
    }
}

Related posts

Recent Viewed