1

HttpResponseMessage returning File from webApi with gibberish characters. I tried setting encoding on header but not helping.

var dataBytes = File.ReadAllBytes(path);
string fileName = Path.GetFileName(path);
var dataStream = new MemoryStream(dataBytes);
HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);
httpResponseMessage.Content = new StreamContent(dataStream);
httpResponseMessage.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
httpResponseMessage.Content.Headers.ContentDisposition.FileName = fileName;
httpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
httpResponseMessage.Content.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
//httpResponseMessage.Content.Headers.Add("Content-Transfer-Encoding", "utf-8");
//httpResponseMessage.Content.Headers.Add("charset", Encoding.ASCII.ToString());
//httpResponseMessage.Content.Headers.Add("charset", "utf-8");
//httpResponseMessage.Content.Headers.ContentEncoding.Add("gzip");
httpResponseMessage.Content.Headers.ContentEncoding.Add("utf-8");
return httpResponseMessage;

All the lines that are commented out were tried and didn't solve the issue.

Thanks.

Emc
  • 11
  • 3
  • If you return a binary file, which is a direct copy of the file on the server it doesn't matter what encoding you set. The file should have the same encoding as the original file. Anyway, do you see that the result file is indeed different than the original file you are sending? – mikus Mar 04 '20 at 14:42

0 Answers0