.NET MVC 通过权限控制文件的下载

禁止用户通过URL直接下载文件

在web.config中配置通过后缀名拒绝访问(需要IIS服务器已安装请求筛选模块)

<security>
  <requestFiltering>
    <fileExtensions>
      <add fileExtension=".zip" allowed="false" />
      <add fileExtension=".ppt" allowed="false" />
      <add fileExtension=".pptx" allowed="false" />
      <add fileExtension=".doc" allowed="false" />
      <add fileExtension=".docx" allowed="false" />
      <add fileExtension=".xls" allowed="false" />
      <add fileExtension=".xlsx" allowed="false" />
    </fileExtensions>
  </requestFiltering>
</security>

通过专门的方法读取并下载文件

在用户生成文件时,将uid作为文件名的第一个参数,当用户通过DownloadDoc方法下载文件时通过当前用于的uid和文件名的uid进行比对,然后下载。也可以将不同用户的文件放在不同的目录中,通过目录名来控制下载请求。

public ActionResult DownloadDoc()
{
    string fileName = Convert.ToString(Request["name"]);
    int uid = RequestHandler.SafeInt(Convert.ToString(System.Web.HttpContext.Current.Session["id"]));
    string[] arr = fileName.Split(new Char[] { '-'});
    if(arr.Length < 1)
    {
        return ErrorResponse("文件格式错误,下载失败");
    }
    if(uid != RequestHandler.SafeInt(Convert.ToString(arr[0])))
    {
        return ErrorResponse("没有权限下载此文件");
    }
    string path = GlobalConst.rootPath + GlobalConst.DocFile + "User" + "/" + fileName;
    if (System.IO.File.Exists(path) == false)
    {
        return ErrorResponse("文件不存在");
    }
    return File(new FileStream(path, FileMode.Open), "application/octet-stream", fileName);
}

猜你喜欢

转载自blog.csdn.net/koastal/article/details/78660677