我正在开发一个网站,上面有一些文件,如果用户根据我的条款有足够的访问权限,我只希望这些文件可供下载。
基本上,我有一个带有下载链接的页面,但只有当用户具有正确的角色并且与我的数据库中的正确属性相关联时,才会显示和激活下载链接。
我面临的问题是我不希望用户能够直接访问该文件,例如,如果他们访问 www.mysite.com/downloads/myfile.pdf - 我不希望他们能够获取该文件,尽管我确实希望能够在他们登录后允许他们下载该文件,并且我已检查他们是否符合我的自定义规则和规定。
我本来打算这样做的,但我相信在停用权限的情况下我将无法这样做。
System.IO.FileInfo file = new System.IO.FileInfo(path);
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.End();
是否有可能实现我的目标?希望我已经充分解释了自己。
谢谢
最佳答案
我相信你的方法是正确的。
这是一个简单的例子:
Response.ContentType = "text/txt";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + "file.txt");
Response.Write(file.ToString());
Response.End();
---- 编辑---- 还有其他好的样本:
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
Response.ContentType = "application/pdf";
Response.Clear();
Response.TransmitFile("UML.pdf");
Response.End();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Way 1</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Send PDF" /><br />
<br />
This page will refresh itself with a PDF file opened in the same instance of IE itself.
Users will not get prompted to Save/Open/Cancel the PDF file.</div>
</form>
</body>
</html>
关于c# - 防止直接访问但允许从页面内下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10604083/