【问题标题】:HTTP Header IssueHTTP 标头问题
【发布时间】:2015-12-12 19:15:15
【问题描述】:

我正在开发 .NET 4.5.3 上的 MVC5 项目。我有 @Html.BeginForm 和 FormMethod.Post 视图,此视图调用 [HttpPost] ActionResult。在控制器中,我从提交的表单中获取必要的 ID,然后将它们传递给导出。

    [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);
    }

在 ExportService 类中我有这个导出方法。

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);
        }
    }

一切正常,但是当我的方法完成工作时,我得到了代码 500 的异常。我通过谷歌搜索了解我的问题,它类似于 1。我知道问题出在 HttpHeader 中,但在我的情况下不明白如何解决它。然后我尝试了if (!Response.IsRequestBeingRedirected) 的解决方案,但我仍然遇到了这个异常。在此之后,我尝试从 GenerateZip 方法返回 ZipFile,而是在 ExportService 类中调用 Response 以在 Controller 中调用它,但我仍然收到此错误。我有一个想法删除 [HttpPost] 属性并以其他方式获取我的 ID,但我的意思是这样做。谁能指出我解决这个问题的任何方向?什么是正确的决定,在这种情况下我应该在哪里调用 Response,是否可以选择编写 jQuery 脚本来防止在 .cshtml 中提交表单?

【问题讨论】:

    标签: c# .net http model-view-controller


    【解决方案1】:

    您正在调用 HttpContext.Current.Response.End();在您的 GenerateZip 方法中,然后尝试在 ControllerAction 中重定向用户。这导致您的“发送响应后无法写入标题”错误。取而代之的是,从 GenerateZip 方法返回一个字节数组或 Stream 对象 (FileStream?),并在 Action 中返回一个 FileResult。文件下载后重定向用户可以(仅?)使用 JavaScript 实现。这是一个例子。 How to return a FileResult AND RedirectToAction in ASP.NET MVC

    【讨论】:

    • 抱歉我迟到的评论。我会试试这个,如果你愿意,我会让你知道结果。感谢您的宝贵时间。
    猜你喜欢
    • 2011-09-01
    • 1970-01-01
    • 2017-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-25
    • 2012-01-22
    • 1970-01-01
    相关资源
    最近更新 更多