0

I'm working on MVC5 project on .NET 4.5.3. I have View with @Html.BeginForm and FormMethod.Post this view calls [HttpPost] ActionResult. In the Controller i get necessary ID's from the submitted form and then pass them for exporting.

    [HttpPost]
    public ActionResult PrepareForExport()
    {
        ExportService export = new ExportService();
        if (Request.Form["button"] != null)
        {
            string selected = Request.Form["button"].ToString();
            export.GeneratePdf(ptoRequestsService.GetByID(Convert.ToInt32(selected)));
        }
        else if (Request.Form["toExport"] != null)
        {
            List<PtoRequest> ptoListForExport = new List<PtoRequest>();
            string selectedItems = Request.Form["toExport"].ToString();
            string[] selectedList = selectedItems.Split(',');
            foreach (var pto in selectedList)
            {
                ptoListForExport.Add(ptoRequestsService.GetByID(Convert.ToInt32(pto)));
            }
            export.GenerateZip(ptoListForExport);
        }
        return RedirectToAction("Requests" + LoggedUser.ID);
    }

And in the ExportService class i have this export method.

public void GenerateZip(List<PtoRequest> approvedPtos)
    {
        byte[] pdfContent = null;
        string dateFormat = "yyyy-MM-dd";
        string filePath = null;
        if (!Directory.Exists(HttpContext.Current.Server.MapPath(@"~/Files/PdfFiles/")))
        {
            Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/Files/PdfFiles/"));
            filePath = HttpContext.Current.Server.MapPath("~/Files/PdfFiles/");
        }
        else
        {
            filePath = HttpContext.Current.Server.MapPath("~/Files/PdfFiles/");
        }
        foreach (var Pto in approvedPtos)
        {
            pdfContent = FillPdfTemplate(Pto);
            string fileName = Pto.User.FirstName + " " + Pto.User.LastName + "_" + Pto.StartDate.ToString(dateFormat) + ".pdf";
            string fileDirectory = filePath + fileName;
            using (FileStream fs = new FileStream(fileDirectory, FileMode.OpenOrCreate))
            {
                fs.Write(pdfContent, 0, pdfContent.Length);
            }
        }
        string zipName = String.Format("Report_{0}.zip", DateTime.Now.ToString("yyyy-mm-dd-HHmmss"));
        string zipFile = filePath + zipName;
        using (ZipFile zip = new ZipFile())
        {
            zip.AddDirectory(filePath);
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.BufferOutput = false;
            HttpContext.Current.Response.ContentType = "application/zip";
            HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
            zip.Save(HttpContext.Current.Response.OutputStream);
            HttpContext.Current.Response.Write(zip.ToString());
            HttpContext.Current.Response.End();
            Directory.Delete(filePath, true);
        }
    }

Everything works fine, but when my method complete the job i got exception with code 500. I do my googling to understand my problem and it is something like this 1. I understand that the problem is in HttpHeader but did not understand how to solve it in my case. Then i tried the solution with if (!Response.IsRequestBeingRedirected) but i still got this exception. After this I tried to return ZipFile from GenerateZip Method and instead calling Response in ExportService class to call it at Controller, but i still got this Error. I have an idea to remove [HttpPost] attribute and to take my ID's in other way but my point is to do it that way. Can anyone point me in any direction to solving this? What is the right decision, where should i call Response for this case, is it option to write jQuery script to prevent submitting form in .cshtml?

1 Answer 1

3

You are calling HttpContext.Current.Response.End(); in your GenerateZip method and then attempting to Redirect the user in the ControllerAction. This is causing your "Headers cannot be written after response is sent" error. Instead of that, return a byte array or Stream object (FileStream?) from the GenerateZip method and return a FileResult in the Action. Redirecting the user after the file download can (only?) be achieved using JavaScript. Here is an example. How to return a FileResult AND RedirectToAction in ASP.NET MVC

1
  • Sorry about my late comment. I will try this and if you want i'll let you know about the result. Thanks for your time. Sep 16, 2015 at 10:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.