MVC 5 FileContentResult操作结果权限和重定向

时间:2016-01-31 15:32:32

标签: asp.net-mvc-5 filecontentresult

我有一个MVC 5应用程序,允许用户下载存储在数据库中的文件。我正在使用FileContentResult操作方法来执行此操作。

我可以在整个应用程序中限制对此方法的访问,但智能用户可以找出操作URL并将这样的内容(localhost:50000 / Home / FileDownload?id = 13)粘贴到他们的浏览器中并可以访问下载只需更改参数即可获得任何文件。

我想限制用户这样做。仅允许具有特定权限的管理员角色和用户只能通过数据库调用来确定下载文件。

我正在寻找的是,如果用户使用该URL下载文件但没有适当的权限,我想用一条消息重定向用户。

我想做类似下面的代码或类似的东西,但是我得到以下错误:无法隐式转换类型' System.Web.Mvc.RedirectToRouteResult'到' System.Web.Mvc.FileContentResult'

我知道我不能在这里使用返回RedirectToAction("索引"),只是寻找有关如何处理这个问题的一些想法。

    public FileContentResult FileDownload(int id)
    {
        //Check user has file download permission
        bool UserHasPermission = Convert.ToInt32(context.CheckUserHasFileDownloadPermission(id)) == 0 ? false : true;

        if (User.IsInRole("Administrator") || UserHasPermission)
        {
            //declare byte array to get file content from database and string to store file name
            byte[] fileData;
            string fileName;
            //create object of LINQ to SQL class

            //using LINQ expression to get record from database for given id value
            var record = from p in context.UploadedFiles
                         where p.Id == id
                         select p;
            //only one record will be returned from database as expression uses condtion on primary field
            //so get first record from returned values and retrive file content (binary) and filename
            fileData = (byte[])record.First().FileData.ToArray();
            fileName = record.First().FileName;
            //return file and provide byte file content and file name

            return File(fileData, "text", fileName);
        }
        else
        {
            TempData["Message"] = "Record not found";

            return RedirectToAction("Index");
        }           
    }

1 个答案:

答案 0 :(得分:5)

由于FileContentResultRedirectToRouteResult都来自ActionResult,因此只需使用ActionResult代替FileContentResult即可获得您的操作的返回类型:< / p>

public ActionResult FileDownload(int id)
{
    if(IsUserCanDownloadFile()) // your logic here
    {
        // fetch the file
        return File(fileData, "text", fileName);
    }
    return RedirectToAction("Index");

}

或者,如果您更喜欢属性,则可以编写自己的authorize属性来检查权限:

public class FileAccessAttribute : AuthorizeAttribute
{
    private string _keyName;

    public FileAccessAttribute (string keyName)
    {
        _keyName = keyName;
    }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        // imagine you have a service which could check the Permission
        return base.AuthorizeCore(httpContext) 
            || (this.ContainsKey
                && _permissionService.CanDownload(httpContext.User.Identity.GetUserId(),
                    int.Parse(this.KeyValue.ToString()));
    }

    private bool ContainsKey
    {
        get
        {
            // for simplicity I just check route data 
            // in real world you might need to check query string too 
            return ((MvcHandler)HttpContext.Current.Handler).RequestContext
                .RouteData.Values.ContainsKey(_keyName);
        }
    }
    private object KeyValue
    {
        get
        {
            return ((MvcHandler)HttpContext.Current.Handler)
                .RequestContext.RouteData.Values[_keyName];
        }
    }
}

现在,您可以在操作中修饰自定义属性:

[FileAccess("id", Roles ="Administrator")]
public FileContentResult FileDownload(int id)
{
    // fetch the file
    return File(fileData, "text", fileName);
}