我一直在研究一个非常古老的ASP.net项目。对于某些特定请求,我想用二进制数据响应客户端,所以我写了下面的代码:
public class MyHttpHandler : IHttpHandler {
public void ProcessRequest(HttpContext context) {
var response = context.Response;
#region weird behavior
response.TrySkipIisCustomErrors = true; // Some post on SO suggests doing this, but doesn't work for me.
response.ClearHeaders(); // Don't know if this helps, but at least won't hurt.
response.StatusCode = 201;
response.ContentType = "application/octet-stream";
response.Headers["X-Custom-Header"] = "foo";
response.Flush(); // Adding Flush() here won't work
#endregion
using(
var input = new FileStream(
@"C:\path\to\binary-file",
FileMode.Open,
FileAccess.Read
)
) {
var output = response.OutputStream;
var bufferSize = 1024;
var buffer = new byte[bufferSize];
var readLength = 0;
do {
readLength = input.Read(buffer, 0, bufferSize);
output.Write(buffer, 0, readLength);
output.Flush();
} while(readLength > 0);
}
}
}
奇怪的是,虽然我得到了正确的响应主体,但我手动设置的状态代码,内容类型和自定义标头都丢失了。我获得的实际内容类型始终为text/html; charset=utf-8
,实际状态代码始终为200
。怎么会这样?