MVC 3:路由到静态页面

时间:2012-05-18 10:05:42

标签: asp.net-mvc-3 routes

今天我提出了对我公司网站的要求(在ASP.NET MVC 3中构建)。

其中一个静态页面,来自我公司网站的pdf文件(来自Content文件夹)显示在Google搜索中。我的公司希望只有登录用户才能访问该pdf文件。

为此我创建了一个Route并用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
        );

在UserController中,我写了一个操作方法OpenContentResources,它将用户重定向到URL

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

但是这段代码无限循环,永远不会被执行。 任何人都可以帮助我解决我的问题。

谢谢...

3 个答案:

答案 0 :(得分:2)

我会这样做:

控制器:

    [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(将其放在您网站的根目录上):

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

这样,您的文件夹将从抓取工具中隐藏,并受到未经身份验证的用户的保护。 在这种情况下,我使用的是表单身份验证,因此如果我在登录前尝试访问文件,则会自动重定向到登录页面。(http://localhost:8080/Home/GetPdf?name=test.pdf)在您的情况下,它可能会有所不同。

参考文献:

Robots.txt

web.config location element

答案 1 :(得分:1)

您必须将pdf文件作为FileResult返回。有关更多信息,请参阅此帖子

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

在您的情况下,操作将如下所示

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

答案 2 :(得分:0)

在测试服务器上托管后问题得到解决。