c# CurrentContext.Response.AddHeader(param1,param2);

2025-04-15 13:21:16
推荐回答(1个)
回答1:

AddHeader()是明确告诉浏览器,下一步处理的指示,比如这是一个下载文件,是打开还是下载,有多少长度,什么格式。
在服务器端可以多次添加header ,header的处理,应该在内容数据发送之前(写入文件字节流之前)
通过Response.Flush() or End() 方法可以将标头发送到客户端。未发送之前,如果是缓存模式,add不会立即发送出去,可以clear()
下面是一个示例
//添加Http头
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachement;filename=" + Server.UrlEncode(info.FullName));
HttpContext.Current.Response.AddHeader("Content-Length", dataToRead.ToString());

while (dataToRead > 0)
{
if (HttpContext.Current.Response.IsClientConnected)
{
int length = stream.Read(buffer, 0, Convert.ToInt32(chunkSize));
HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Clear();
dataToRead -= length;
}
else
{
//防止client失去连接
dataToRead = -1;
}
}