0

I have an ASP.NET MVC application and I want the logged in users be able to download some files inside application path, and avoid not logged in users to download files.

I want this folder to be in the root of project folder

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Hamid Noahdi
  • 1,585
  • 2
  • 11
  • 18
  • You can get some help here: https://stackoverflow.com/questions/36775942/how-do-i-serve-static-files-only-to-authorized-users – Saeid Amini Jul 14 '19 at 12:42
  • @SaeidAmini That only works for core. – Erik Philips Jul 14 '19 at 12:43
  • How about this one? I think it can help. https://www.hanselman.com/blog/BackToBasicsDynamicImageGenerationASPNETControllersRoutingIHttpHandlersAndRunAllManagedModulesForAllRequests.aspx – Saeid Amini Jul 14 '19 at 13:03

1 Answers1

2

It depends that how would you like to implement this scenario :

First scenario : you could put your download links inside these block of code, to prevent from showing to unauthorized users.

View page :

 @if (Utility.CheckActionPermission("ActionName", "ControllerName", "AreaName"))
            {
                 // your download link should be here               
            }

Controller :

public static bool CheckActionPermission(string actionName, string controllerName, string areaName)
    {
        var accessUrl = string.Concat(areaName, "/", controllerName, "/", actionName);
        return ((CustomPrincipal)HttpContext.Current.User).Access.Any(a => a.Url == accessUrl);
    }

Second scenario : Put all of your links freely to show to every user but you need to validate the user's authority when the download link clicked :

View:

@Html.ActionLink("File Name", "DownloadFile", "ControllerName", new { fileName= @Model.FileName }, null)

Controller

    [Authorize]
    public static bool DownloadFile(string fileName)
    {
        var filePath = Path.Combine(PathConstants.DownloadFolder, fileName);

        //some code to download the file 
    }
Matt Qafouri
  • 1,449
  • 2
  • 12
  • 26
  • 1
    When user types the file path directly in the browser he/she can download the file. i want to prevent this, but i do not know how to do it. – Hamid Noahdi Jul 15 '19 at 05:49
  • 1
    You could use temporary file names : To throw confusion and complication into the mix, some vendors dynamically generate a file name using a GUID or some other cryptic naming technique. They also tend to make the file available for download only for a limited time. for a further explanation please visit this page :[link](https://www.codemag.com/Article/0703031/Protect-Your-Downloadable-Files-Using-HTTP-Handlers) – Matt Qafouri Jul 15 '19 at 06:22
  • It was very helpful – Hamid Noahdi Mar 12 '20 at 17:47