简体   繁体   中英

MVC 4 mapping files in directory to controller action to ensure authorized access to documents

If I have a file in a directory on my website:

~/documents/file1.pdf

How can I force requests to the following url to go through a controller:

www.mydomain.com/documents/file1.pdf

The controller would then look something like

[Authorize]
public DocumentsController : Controller
{
     public FileResult Index(string fileName)
     {
          //Check user has permission to view file



          return File(...);
     }
}

I got round this by putting the documents directory in the App_Data folder so it's not accessible to the public and the using the document's ID from the database to retrieve the relevant information eg

/documents/21

I think I prefer this approach anyway to my initial plan because it abstracts the identity of the path and document title far more thoroughly as the controller path can be anything and doesn't have to map to a physical directory path.

This is not difficult, so long as you can make some assumptions.

First, you create your action method as you propose:

[Authorize]
public DocumentsController : Controller
{
     public FileResult Index(string fileName)
     {
          //Check user has permission to view file

          return File(...);
     }
}

Next, you create a route:

routes.MapRoute(
    name: "Documents",
    url: "documents/{fileName}",
    defaults: new { controller = "Documents", action = "Index" }

You may be required to relax the url validation requirements by adding the following to web.config (this only works in IIS7-8 though as far as I know, IIS6 would require an http module I think):

<httpRuntime relaxedUrlToFileSystemMapping="true" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM