【发布时间】: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