从 url 下载 pdf 最佳方法

Kac*_*hou 3 .net c# asp.net asp.net-mvc

我使用下面的代码从网址下载 Pdf,我想知道什么是最佳实践,我只关心性能和文件大小,谢谢。

using( WebClient wc = new WebClient() )
{
  byte[] data = wc.DownloadData("http://localhost:81/File/sample.pdf");

  Response.Clear();
  Response.ContentType = "application/pdf";
  Response.AppendHeader( "Content-Disposition" , "attachment;filename=data.pdf" );
  Response.BufferOutput = true;
  Response.AddHeader("Content-Length", data.Length.ToString());
  Response.BinaryWrite(data);
  Response.End();

}
Run Code Online (Sandbox Code Playgroud)

Lui*_*iso 6

如果您担心性能/效率/安全性,我建议使用该框架,HttpClient您可以这样做:

using(var client = new HttpClient())
{
    var stream = await client.GetStreamAsync(url);

    // OR to get the content of the file as you do now
    var data = await client.GetByteArrayAsync(url);

    // do whatever you need to do with your file here
}
Run Code Online (Sandbox Code Playgroud)