c# - 防止直接访问但允许从页面内下载文件

标签 c# asp.net iis permissions download

我正在开发一个网站,上面有一些文件,如果用户根据我的条款有足够的访问权限,我只希望这些文件可供下载。

基本上,我有一个带有下载链接的页面,但只有当用户具有正确的角色并且与我的数据库中的正确属性相关联时,才会显示和激活下载链接。

我面临的问题是我不希望用户能够直接访问该文件,例如,如果他们访问 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();

---- 编辑---- 还有其他好的样本:

http://www.dotnetscraps.com/dotnetscraps/post/4-ways-to-send-a-PDF-file-to-the-IE-Client-in-ASPNET-20.aspx

<%@ 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/

相关文章:

c# - 使用 DateTime 解析时如何知道时间部分是否存在

c# - 异步更新 ASP.NET 面板

c# - 使用 Linq 进行 GroupBy 和选择

c# - 如何从 Canvas 中的隐藏代码打开图像并让用户在此图像上绘图

c# - 如何在Web应用程序中显示互联网连接速度?

c# - ASMX - 未在 IIS 上调用 Web 方法

iis - 授予权限 IIS 7 Microsoft Windows Server 2008

iis - 为什么我们的后端程序员使用重定向以这种方式处理 SSL?

c# - 从脚本创建数据库时关键字 'USE' 错误附近的语法不正确

c# - 使用数组填充列表框?