Так что есть некоторые вопросы и ответы на SO, но никто не помог мне, и я понял, что вызывает проблему, но не знаю, что делать.
Мой ReadFiles
Контроллер:
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
}
Когда я запускаю это, оно ВСЕГДА входит в Global.asax
в Application_Error
:
protected void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
Debug.WriteLine(Response.StatusCode);
Debug.WriteLine(ex.GetType().Name);
///...
}
Исключение составляет Server cannot set status after HTTP headers have been sent
.
Странные вещи длямне, StatusCode
в Application_Error
- 200
, Исключением является HttpException
(который должен быть перехвачен в контроллере).
Поэтому я перепробовал много решений, написанных на SO (поставьте ихв комментарии), но ничего не получалось.Итак, я понял, в чем моя проблема.Установка contentType в начале не помогает.Когда я комментирую эту строку:
//contentType = Response.ContentType;
Application_Error
не затрагивается и работает нормально (хорошо, я получаю простой текст в браузере, и загрузка не появляется).Очевидно, мне нужно Respones.ContentType
в возвращении файла.Это работает только тогда, когда ContentType является пустой строкой.Так что return File(Response.OutputStream, "", fileName);
работает.Как я могу решить эту проблему или где я должен поставить тип контента, чтобы он работал?
Может ли это быть проблема на стороне сервера?