Server cannot add header after sending HTTP headers

My code is shown below after creating the CSV file, I want to download the file, so I use the code below. but his throwing error "Server cannot add a header after sending HTTP headers" in "Response.AddHeader" ("Content-disposition", "attachment; filename =" + fileCSV + "\" ";" place. Its loading, but the browser is not redirecting to the same page.

string[] header = { "Error Occurred On", "Controller Name", "Action Name", "Exception Occurred", "Stack Trace Description", "InnerException Occurred", "Stack Trace InnerException Occurred " };

The code:

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();
}
+4
source share
3 answers

You cannot redirect after downloading the file, you are trying to perform 2 actions in which you can only do the first.

() .

Edit: -

, 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>
+2

HTTP . , , - .

+1

, , Response.Flush Response.End, HttpContext.ApplicatiohInstance.CompleteRequest(). .

0

All Articles