So there are some Q&A on SO, but noone helped me and i figured out what causes the problem, but don't know what to do.
My ReadFiles
Controller:
public FileStreamResult ReadFiles(int id, string fileName)
{
//Response.BufferOutput = true;
string extension = Path.GetExtension(fileName).ToLower();
try
{
using (NpgsqlConnection con = new NpgsqlConnection(_Connection))
{
con.Open();
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
cmd.Connection = con;
cmd.CommandText = "...";
using (NpgsqlDataReader reader = cmd.ExecuteReader())
{
byte[] chunk = new byte[10 * 1024];
string contentType = String.Empty;
if (reader.Read())
{
if (extension.Length > 0)
{
Response.Clear();
Response.Buffer = true;
//Response.BufferOutput = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite((byte[])reader["f_file"]);
}
else
{
long read;
long offset = 0;
read = reader.GetBytes(0, offset, chunk, 0, chunk.Length);
chunk = new byte[read];
do
{
//write output
}
while (read > 0);
}
}
string responseHeader = HelperClass.GetExtensionString(extension);
Response.AddHeader("Content-Type", responseHeader);
//download file + opens pdf NOT in browser
fileName = fileName.Replace("/", "_");
Response.AddHeader("Content-Disposition", "attachment; filename*=UTF-8''" + Uri.EscapeDataString(fileName));
contentType = Response.ContentType;
//Response.SuppressFormsAuthenticationRedirect = true;
//Response.StatusCode = 200;
//Response.Flush();
//Response.Clear();
Response.End();
return File(Response.OutputStream, contentType, fileName);
}
}
}
}
catch (HttpException ex)
{
Debug.WriteLine(ex.Message);
}
catch (Exception ex)
{
....
}
//finally
//{
// Response.Clear();
// Response.End();
//}
return null
}
When I am running this, it is ALWAYS going into the Global.asax
into the Application_Error
:
protected void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
Debug.WriteLine(Response.StatusCode);
Debug.WriteLine(ex.GetType().Name);
///...
}
The exception is Server cannot set status after HTTP headers have been sent
.
Weird things for me, the StatusCode
in the Application_Error
is 200
, the Exception is an HttpException
(which should be catched in the controller).
So I tried many solutions written on SO (put them into comments), but nothing worked. So I figured out what is my problem. Setting the contentType at the beginning doesn't help. When I am commenting this line:
//contentType = Response.ContentType;
Application_Error
isn't touched and it is running well (Ok I get the plain text in the browser and no Download appears). Obviously I need the Respones.ContentType
in the File returning. It is only working when the ContentType is an empty string. So return File(Response.OutputStream, "", fileName);
is working. How I can solve this problem or where do I have to put the content type, that this is working?
Can it be a Serverside problem?