c# - 什么是 HttpContext.Current.Response
问题描述
我试图创建一个新端点以从服务器下载文件。从https://forums.asp.net/t/2010544.aspx?Download+files+from+website+using+Asp+net+c+获得了示例,这就是我最终的结果:
[Route("{id}/file")]
[HttpGet]
public IHttpActionResult GetFile(int id)
{
var filePath = $"C:\\Static\\File_{id}.pdf";
var response = HttpContext.Current.Response;
var data = new WebClient().DownloadData(filePath);
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.Buffer = true;
response.AddHeader("Content-Disposition", "attachment");
response.BinaryWrite(data);
response.End();
return Ok(response);
}
但我不确定我是否需要所有这些:
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.Buffer = true;
response.BinaryWrite(data);
response.End();
这些有什么作用?
解决方案
响应对象是包含与客户端在当前请求被返回后将从服务器接收到的响应相关的所有内容的对象。
response.Clear(); -> Will clear the content of the body of the response ( any html for example that was supposed to be served back, you can remove this)
response.ClearContent(); -> will clear any content in the response ( that is why you can remove the previous Clear call i think )
response.ClearHeaders(); -> Clears all headers asscociated with the response. (For example a header might tell the client there is 'encoding:gzip')
response.Buffer = true; -> enables response buffer
response.BinaryWrite(data); -> Appends your binary data to the content of the response( you cleared it earlier so now only this is contained)
response.End(); -> Terminates the current response handling and returns the response to the client.
在这里查找更多内容和更好的解释!
推荐阅读
- html - 媒体查询适用于 chrome 但不适用于移动设备
- xcode - 用于动画的 SwiftUI 或 UIKit?
- email - 根据列中的值发送电子邮件的脚本 - 脚本问题
- yaml - 是否可以在可折叠的 Yaml 文本块中为一行添加额外的缩进而不破坏折叠?
- firebase-realtime-database - 来自 REST API 的 Firebase 流式传输
- c# - 在 .NET Core 中使用一个连接通过 FTP 下载多个文件
- python - 您如何使用输出中的 final_simplex 在 scipy.optimize.minimize 中使用 Nelder-Mead 方法估计参数误差/不确定性
- html - 使引导列占据整个页面宽度(或至少 90%)
- python - Discord.py 代码未正确读取/写入 JSON 文件
- c++ - 在除法上显示小数,即使结果为整数