首页 > 解决方案 > 什么是 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();

这些有什么作用?

标签: c#

解决方案


响应对象是包含与客户端在当前请求被返回后将从服务器接收到的响应相关的所有内容的对象。

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. 

在这里查找更多内容和更好的解释


推荐阅读