0

Here is the situation.

I have an action method, which returns a file, called "GetDocument" in "Documents" controller. It has one parameter of type Document, which contains document path, title, type etc.

I have a View for an entity, which has some documents attached with it. For example, a news story, with attached documents. On this view I show various links for the documents which the end user should be able to download.

The question is: How do I create such links which pass proper "Document" object to the "GetDocument" Action Method?

Edit: I do not want to show full path of the document to the user. In fact, I would like that I store documents in App_Data folder, so that they cannot be downloaded otherwise.

Thanks!

2 Answers 2

2

You could use an ActionLink:

@Html.ActionLink(
    "Download", 
    "GetDocument", 
    new {
        path = "report.pdf",
        type = "application/pdf"
    }
)

and then:

public ActionResult GetDocument(Document doc)
{
    var appData = Server.MapPath("~/App_Data");
    var file = Path.Combine(appData, doc.Path);
    file = Path.GetFullPath(file);
    if (!file.StartsWith(appData))
    {
        // Ensure there are no cheaters trying to read files
        // outside of the App_Data folder like "../web.config"
        throw new HttpException(403, "Forbidden");
    }
    if (!File.Exists(file))
    {
        return HttpNotFound();
    }
    return File(file, doc.Type, Path.GetFileName(file));
}
4
  • 1
    How well do ASP.NET handle relative paths? Can the user enter "../../somethingsecret.config"?
    – jgauffin
    May 20, 2011 at 6:40
  • @jgauffin, excellent remark. I've updated my answer to take it into account. May 20, 2011 at 6:42
  • Thanks for the answer! A question from security point of view: Still the user will be able to see the path (relative to App_Data) using your approach. Is it fine?
    – virtualmic
    May 20, 2011 at 7:46
  • @virtualmic, yes the user will be able to see the path App_Data but he will not be able to access it directly. He needs to use the GetDocument action but he can access any file inside if he knows the name. If you want to implement a more fine-grained security it is recommended to store paths into a database, associate them with user permissions, etc... May 20, 2011 at 8:16
0

why would your controller need to know about the full document when the action is called? surely your documents have ids. take the id, ask your repository for the domain object, and then get the file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.