代码之家  ›  专栏  ›  技术社区  ›  Jee Mok ecanf

什么是httpcontext.current.response

c#
  •  -1
  • Jee Mok ecanf  · 技术社区  · 8 年前

    我试图创建一个新的端点来从服务器下载文件。示例来自 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();
    

    这些是做什么的?

    1 回复  |  直到 8 年前
        1
  •  1
  •   MKougiouris    8 年前

    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. 
    

    here!