3

今天我提出了对我公司网站的要求(在 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");
    }

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

谢谢 ...

4

3 回答 3

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");
        }
    }

网络配置:

  <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)在您的情况下,它可能会有所不同。

参考:

机器人.txt

web.config 位置元素

于 2012-05-18T12:39:55.377 回答
1

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

ASP.NET MVC - 如何为 PDF 下载编写代码?

在你的情况下,动作看起来像

public ActionResult OpenContentResources()
{
    return File("~/Content/PDF/ABC.pdf", "application/pdf");
}
于 2012-05-18T10:19:38.763 回答
0

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

于 2012-05-22T11:10:31.523 回答