为什么写入响应流当内容被损坏
-
19-09-2019 - |
题
我想写出响应流 - 但它失败,它以某种方式破坏数据...
我希望能够编写存储别处的HttpWebResponse,所以我不能用“WriteFile的”这个流,再加上我想了好MIME类型做到这一点,但它不能为所有的人 - 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