今天我提出了对我公司网站的要求(在 ASP.NET MVC 3 中构建)。
我公司网站的静态页面之一(来自内容文件夹)显示在 Google 搜索中。我的公司希望只有登录用户才能访问该 pdf 文件。
为此,我创建了一条路线并用 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");
}
但是这段代码进入无限循环并且永远不会被执行。 任何人都可以帮助我解决我的问题吗?
谢谢...
最佳答案
我会这样做:
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");
}
}
网络配置:
<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
)在您的情况下可能会有所不同。
引用文献:
关于asp.net-mvc-3 - MVC 3 : Routing to Static Pages,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10650601/