asp.net-mvc - 在 MVC3 中如何拦截文件请求以检查权限?

标签 asp.net-mvc asp.net-mvc-3 file-permissions

我的文件上传在 ASP MVC3 网站上运行良好。目前,这些文件保存在网站上名为“Files”的文件夹中。用户可以上传任何类型的文件(例如 myphoto.jpg、mydocument.docx 等)。

当用户上传文件时,我会在 SQL 数据库中存储有关该文件的信息以及上传者等信息。

我的问题:

  1. 如何拦截对文件 URL(例如/Files/myphoto.jpg)的 GET 请求以查看是否允许用户查看该文件? (基于他们在申请中的权利)?我不喜欢在允许访问之前编写路由约束来检查数据库的想法。
  2. 理想情况下,我希望将文件存储在与网站文件位置不同的位置,但网站可以根据请求确定文件及其位置,但仍将其提供给该位置,就好像它位于该位置一样请求(正确的内容类型 header 等)。

最佳答案

您可以添加 Controller 来服务器文件。

public class FileController : Controller
{

    private IFileStore _fileStore;

    public FileController(IFileStrore fileStore)
    {
        this._fileStore = fileStore; 
    }

    public ActionResult Index(string fileName)
    {
        // Do a database look up if the user has permission
        if (_fileStore.HasPermission(fileName, User))
        {
            // Flush the file content if the user has permission
            var myfile = _fileStore.GetFile(fileName);
            Response.ClearContent();
            Response.AddHeader("Content-Disposition", "attachment; filename=" + myfile.FileName);
            Response.AddHeader("Content-Length", myfile.Length.ToString());

            Response.ContentType = myfile.Extension.ToLower();
            Response.WriteFile(myfile.FullName, false);
            Response.Flush();
            Response.Close();
        }
        else
        {
            // Return a Access Denied page
            return View("NoPermission");
        }
    }

}

关于asp.net-mvc - 在 MVC3 中如何拦截文件请求以检查权限?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11736069/

相关文章:

.net - EF在父删除时将外键设置为空

asp.net-mvc - 我如何加密通过 $.AJAX 发送的数据 - asp.net Mvc 3

c# - 具有匿名类型模型类的 Razor View 。有可能的?

c# - 使用 C# 将文件/文件夹添加到 Program Files x86 文件夹

php - move_uploaded_file 给出 "failed to open stream: Permission denied"错误

javascript - 未捕获的 TypeError : (intermediate value). Pie 不是函数 -Chart.js

c# - 如何在使用 asp.net Identity 关闭浏览器后保留登录信息?

asp.net-mvc - 在 MVC3 中为图像指定 src 的正确方法

asp.net-mvc - 无法在 Windows 10 中使用命令行安装网站 msi

c# - 当子目录不存在时,将文件上传到具有特定名称的子目录?