服务器无法在HTTP头已发送后附加标头。

4
以下是创建CSV文件后的代码,我想要下载这个文件,所以使用了下面的代码。但是它会在“Response.AddHeader("Content-disposition", "attachment; filename=" + fileCSV + "\"");"处抛出错误“服务器无法在HTTP头已发送之后附加头”。它正在下载,但浏览器没有重定向到同一页。
string[] header = { "Error Occurred On", "Controller Name", "Action Name", "Exception Occurred", "Stack Trace Description", "InnerException Occurred", "Stack Trace InnerException Occurred " };

代码如下:
DataTable dt = new DataTable();
for (int e = 0; e < header.Length; e++)
{
    dt.Columns.Add(header[e], typeof(string));
}
StringBuilder sb = new StringBuilder();
IEnumerable<string> columnNames = dt.Columns.Cast<DataColumn>().Select(column => column.ColumnName);
sb.AppendLine(string.Join(",", columnNames));
dt.DefaultView.RowFilter = "[Exception Occurred] LIKE '%" + keyword + "%'";
DataTable dtFilter = new DataTable();
dtFilter = dt.DefaultView.ToTable();
foreach (DataRow row in dtFilter.Rows)
{
    IEnumerable<string> fields = row.ItemArray.Select(field => field.ToString());
    sb.AppendLine(string.Join(",", fields));
}
System.IO.File.WriteAllText(fileCSV, sb.ToString());

byte[] bytes = Encoding.ASCII.GetBytes(sb.ToString());
if (bytes != null)
{
    Response.Clear();
    Response.ContentType = "text/csv";
    //Response.AddHeader("Content-Length", bytes.Length.ToString());
    Response.AddHeader("Content-disposition", "attachment; filename=" + fileCSV);
    Response.BinaryWrite(bytes);
    Response.Flush();
    Response.End();
}

2
这段代码之前发生了什么?错误本身非常明显。 - CodeCaster
在使用datatable创建csv文件之前,需要将datatable中的数据添加到csv文件中。 - Prashant G Rathod
4个回答

2

您不能在下载文件后重定向,您正在尝试执行两个操作,而您只能执行第一个操作。

我建议您在新窗口(弹出窗口)中下载文件,如果需要的话,请重定向主页面。

编辑:

您可以使用window.open打开文件下载操作以强制下载。

示例:

<a href="Action/RedirectPage" data-file="Action/DownloadCVS" class="file-download">Download File</a>

<script>
  $(function() {
      $('a.file-download').click(function() {
         window.open($(this).data('file'));
      }); 
  });
</script>

如何在新的弹出窗口中实现。你能分享一些代码示例吗? - Prashant G Rathod
嗨,这个问题已经解决了,它是一个循环问题。但是在下载CSV文件后,浏览器没有加载页面。 - Prashant G Rathod

1
在HTTP中,每个请求只有一个响应。因此,这个错误意味着您已经向响应发送了某些内容。

1
我在下载以下显示函数之前进行操作。据我所知,我没有发送其他请求。 DataTable dtFilter = new DataTable(); dtFilter = dt.DefaultView.ToTable(); foreach (DataRow row in dtFilter.Rows) { IEnumerable<string> fields = row.ItemArray.Select(field => field.ToString()); sb.AppendLine(string.Join(",", fields)); } System.IO.File.WriteAllText(fileCSV, sb.ToString()); - Prashant G Rathod

0

不确定您是否仍在寻找答案,但是与Response.Flush和Response.End不同,尝试使用HttpContext.ApplicationInstance.CompleteRequest()。当尝试直接写入请求流时,它解决了我很多问题。


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接