Search code examples
asp.net-mvcauthorize

How to restrict access to a certain file in MVC


I am using ASP.Net MVC, and I was wondering how can I restrict access to a certain file. I read about using [Authorize] but it applies to controllers and actions. I try to use within the web.config but its extremely advise not to do that cause MVC becomes confuse when seeing multiple .

My file is within the base of the application, e.g. /MyApp/MyFile. I would like to do is, when a user navigates to the file. The user will see, correct me if I'm wrong, the HTTP 401 error or something.


Solution

  • In order to do this stick the files in a folder under App_Data which will prevent direct access and then you will need to create a controller to handle access to the file. First create a route:

    routes.MapRoute("", "Files/{file}", new { controller = "File", action = "View" });
    

    and then apply the Authorize attribute to the action and use

    return File(...);
    

    to actually return the file to the user.