简体   繁体   中英

How to open a pdf file using the controller? Asp.net MVC

I'm trying to open a PDF file located inside the folder (Content/extras) in my app using the controller and is not working for me. The error I'm receiving is

"Could not find file 'C:/..../Content/extras/PDFName'" Exception details: System.IO.FileNotFoundException: Could not find file 'C:/..../Content/extras/PDFName'"

So basically it says that it can't find the file but the file is 100% in that location and the name is correct. I do notice though that is trying to find 'PDFName' instead of 'PDFName.pdf' so maybe that's what's wrong and is the 'MimeMapping' in the controller that is not coded correctly.

Here is my code:

Controller

public FileResult PDFFlyer()
{
    string path = Server.MapPath(String.Format("~/Content/extras/PDFName"));

    string mime = MimeMapping.GetMimeMapping(path);

    return File(path, mime);
}

RouteConfig

    routes.MapRoute(
        name: "PDFFlyer",
        url: "{filename}",
        defaults: new { controller = "PDF", action = "PDFFlyer", filename = 
        UrlParameter.Optional }
    );

The cshtml file

<a class="dropdown-item" href="@Url.Action("PDFFlyer", "PDF")" target="_blank">PDF Flyer</a>

What am I doing wrong? Again I'm guessing is the 'MimeMapping' Controller code that is incorrect because it doesn't seem to be looking for the '.pdf.' and is only looking for the PDFName, but not really sure what's wrong. Any suggestions? Thanks.

I finally figured it out. I just needed to add the .pdf extention into the PDFName on the 'path' variable. The confusion was cause I thought the 'path' was only the path with just the PDFName and not the .pdf extension, and then the 'mime' would have the '.pdf' extention. But no, the 'path' should have the whole path of were the file is INCLUDING the .pdf extention, and then the 'mime' variable is marely, as I understand, just to identity the type of the file.

So, the Controller, which is the only thing I changed for it to work, looks like this:

public FileResult PDFFlyer()
{
    //include the .pdf extention at the end
    string path = Server.MapPath(String.Format("~/Content/extras/PDFName.pdf")); 

    string mime = MimeMapping.GetMimeMapping(path);

    return File(path, mime);
}

The only thing that doesn't work correctly is the Route URL, but that's for another question in another thread. But at least the pdf file is showing correctly which was the purpose of this question.

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