我正在开发一个网站,上面有一些文件,如果用户按照我的条件有足够的访问权限,我只想下载这些文件。

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

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

10-14 18:55
查看更多