응답 스트림에 쓸 때 콘텐츠가 손상된 이유
-
19-09-2019 - |
문제
응답 스트림에 글을 쓰려고 노력하고 있습니다. 그러나 실패합니다. 어떻게 든 데이터를 손상시킵니다 ...
나는 httpwebrepresponse에 다른 곳에 저장된 스트림을 쓸 수 있으므로 이것을 위해 '쓰기 파일'을 사용할 수 없으며 여러 마임 유형에 대해 이것을하고 싶지만 모두에게 실패합니다 - mp3, pdf 등. ..
public void ProcessRequest(HttpContext context)
{
var httpResponse = context.Response;
httpResponse.Clear();
httpResponse.BufferOutput = true;
httpResponse.StatusCode = 200;
using (var reader = new FileStream(Path.Combine(context.Request.PhysicalApplicationPath, "Data\\test.pdf"), FileMode.Open, FileAccess.Read, FileShare.Read))
{
var buffer = new byte[reader.Length];
reader.Read(buffer, 0, buffer.Length);
httpResponse.ContentType = "application/pdf";
httpResponse.Write(Encoding.Default.GetChars(buffer, 0, buffer.Length), 0, buffer.Length);
httpResponse.End();
}
}
미리 건배
해결책
바이트가 아닌 캐릭터를 쓰고 있기 때문입니다. 캐릭터는 확실히 바이트가 아닙니다. 그것은 인코딩되어야하며, 그것이 당신의 "부패"가 들어오는 곳입니다. 대신 이렇게하십시오.
using (var reader = new FileStream(Path.Combine(context.Request.PhysicalApplicationPath, "Data\\test.pdf"), FileMode.Open, FileAccess.Read, FileShare.Read))
{
var buffer = new byte[reader.Length];
reader.Read(buffer, 0, buffer.Length);
httpResponse.ContentType = "application/pdf";
httpResponse.BinaryWrite(buffer);
httpResponse.End();
}
제휴하지 않습니다 StackOverflow