如何在不暴露URL的情况下在MVC中提供文件?

dev*_*kle 6 asp.net asp.net-mvc azure azure-web-sites azure-storage-files

我有一个树查看器,允许用户浏览文件和子目录,当用户到达文件时,网站将转到https://website.com/path/subpath/file.pdf.假设我可以识别用户正在查看文件,将发生以下情况:

  • 控制器将生成SAS密钥以从Azure检索文件.
  • 控制器将获得一个网址: https://myaccount.files.core.windows.net/path/?=accesskey

虽然查看此访问密钥的用户没有问题,但它最终会过期,并且对于用户为页面添加书签,我希望用户不会被重定向到Azure路径,而是让ASP.NET输出文件好像用户还在https://website.com/path/subpath/file.pdf

所以最后的问题基本上是:

如何在不强制下载和不显示文件路径/ url的情况下输出文件?

Shy*_*yju 7

您可以尝试从存储中读取文件作为字节数组,并使用该File方法从操作方法返回它.

public ActionResult View(int id)
{
  // id is a unique id for the file. Use that to get the file from your storage.
  byte[] byteArrayOfFile=GetFileInByteArrayFormatFromId(id);
  return File(byteArrayOfFile,"application/pdf");
}
Run Code Online (Sandbox Code Playgroud)

假设GetFileInByteArrayFormatFromId从存储/ azure读取后返回文件的字节数组版本.您可以考虑缓存环境中的一些文件,这样您就不需要通过azure来获取每个请求.

如果您可以将文件作为文件流读取,则该File方法也会出现重载

public ActionResult View(int id)
{
  // id is a unique id for the file. Use that to get the file from your storage.
  FileStream fileStream = GetFileStreamFromId(id);;
  return File(fileStream, "application/pdf","Myfile.pdf");
}
Run Code Online (Sandbox Code Playgroud)

如果您的服务器中有可用的文件(缓存文件),您可以使用File方法的另一个重载,您将传递路径而不是字节数组.

public ActionResult View(int id)
{
  var f = Server.MapPath("~/Content/Downloads/sampleFile.pdf");
  return File(f,"application/pdf");
}
Run Code Online (Sandbox Code Playgroud)

如果浏览器支持显示响应的内容类型,则响应将显示在浏览器中.大多数主流浏览器都支持渲染pdf文件.

File方法的另一个重载是获取浏览器的保存/下载对话框将使用的下载文件名,以便用户可以将其保存到本地计算机和/或打开.

public ActionResult View(int id)
{
    var pathToTheFile=Server.MapPath("~/Content/Downloads/sampleFile.pdf");
    return File(pathToTheFile, MimeMapping.GetMimeMapping(pathToTheFile),"Myfile.pdf");
}
public ActionResult ViewFromByteArray(int id)
{
    byte[] byteArrayOfFile=GetFileInByteArrayFormatFromId(id);
    return File(byteArrayOfFile, "application/pdf","Myfile.pdf");
}
Run Code Online (Sandbox Code Playgroud)

有了这个,用户将从浏览器获得下载提示.