shakti
shakti

Reputation: 191

MVC 3 : Routing to Static Pages

today i came up with a requirement for my company website (build in ASP.NET MVC 3).

One of the static pages, a pdf file (from Content folder) from my companies website is shown up in Google searches. My company wants that pdf file to be accessible to only logged in users.

For that i created a Route and decorated it with RouteExistingFiles = true;

        routes.RouteExistingFiles = true;
        routes.MapRoute(
            "RouteForContentFolder", // Route name
            "Content/PDF/ABC.pdf", // URL with parameters
            new { controller = "User", action = "OpenContentResources", id = UrlParameter.Optional } // Parameter defaults
        );

In UserController I wrote an action method OpenContentResources which would redirect the user to the URL

    [CompanyAuthorize(AppFunction.AccessToPDFFiles)]
    public ActionResult OpenContentResources()
    {
        return Redirect("http://localhost:9000/Content/PDF/ABC.pdf");
    }

But this code goes in infinite loop and never gets executed. Can any one help me around with my concern.

Thanks ...

Upvotes: 3

Views: 3368

Answers (3)

shakti
shakti

Reputation: 191

The problem got solved after hosting it on test server.

Upvotes: 0

lucask
lucask

Reputation: 2290

I would do it this way:

Controller:

    [Authorize]
    public ActionResult GetPdf(string name)
    {
        var path = Server.MapPath("~/Content/Private/" + name);
        bool exists = System.IO.File.Exists(path);
        if (exists)
        {
            return File(path, "application/pdf");
        }
        else
        {
            // If file not found redirect to inform user for example
            return RedirectToAction("FileNotFound");
        }
    }

web.config:

  <location path="Content/Private" allowOverride="false">
    <system.web>
      <authorization>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>

robots.txt (place it on the root of Your site):

User-agent: *
Disallow: /Content/Private/

This way your folder will be hidden from crawlers and protected from unauthenticated users. In this case I was using Forms Authentication so I was automatically redirected to login page if I was trying to access file before logging in. ( http://localhost:8080/Home/GetPdf?name=test.pdf ) In Your case it might be different.

References:

Robots.txt

web.config location element

Upvotes: 2

Juraj Such&#225;r
Juraj Such&#225;r

Reputation: 1117

You have to return the pdf file as a FileResult. See this post for more information

ASP.NET MVC - How do I code for PDF downloads?

In your case the action will looks like

public ActionResult OpenContentResources()
{
    return File("~/Content/PDF/ABC.pdf", "application/pdf");
}

Upvotes: 1

Related Questions