创建临时链接以供下载

Ily*_*okh 4 asp.net webpage file download hyperlink

我使用ASP.NET
我需要给用户临时链接从服务器下载文件.
它应该是一个临时链接(页面),可以在短时间内使用(例如12小时).如何生成此链接(或带链接的临时网页)?

Hug*_*h W 9

这是一个相当完整的例子.

首先是使用秘密盐加上到期时间来创建短十六进制字符串的函数:

public static string MakeExpiryHash(DateTime expiry)
{
    const string salt = "some random bytes";
    byte[] bytes = Encoding.UTF8.GetBytes(salt + expiry.ToString("s"));
    using (var sha = System.Security.Cryptography.SHA1.Create())
        return string.Concat(sha.ComputeHash(bytes).Select(b => b.ToString("x2"))).Substring(8);
}
Run Code Online (Sandbox Code Playgroud)

然后是一个生成一周到期链接的片段:

DateTime expires = DateTime.Now + TimeSpan.FromDays(7);
string hash = MakeExpiryHash(expires);
string link = string.Format("http://myhost/Download?exp={0}&k={1}", expires.ToString("s"), hash);
Run Code Online (Sandbox Code Playgroud)

最后,如果给出了有效链接,则发送文件的下载页面:

DateTime expires = DateTime.Parse(Request.Params["exp"]);
string hash = MakeExpiryHash(expires);
if (Request.Params["k"] == hash)
{
    if (expires < DateTime.UtcNow)
    {
        // Link has expired
    }
    else
    {
        string filename = "<Path to file>";
        FileInfo fi = new FileInfo(Server.MapPath(filename));
        Response.ContentType = "application/octet-stream";
        Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
        Response.AddHeader("Content-Length", fi.Length.ToString());
        Response.WriteFile(fi.FullName);
        Response.Flush();
    }
}
else
{
    // Invalid link
}
Run Code Online (Sandbox Code Playgroud)

您应该在一些异常处理中包装以捕获损坏的请求.


Ant*_*lev 6

http://example.com/download/document.pdf?token=<token>
Run Code Online (Sandbox Code Playgroud)

<token>部分是关键.如果您不想涉及数据库,请加密链接创建时间,将其转换为URL安全的Base64表示并为用户提供该URL.当它被请求时,解密token并比较存储在那里的日期与当前日期和时间.

或者,您可以有一个单独的DownloadTokens表,它将所述tokens(可以是GUID)映射到到期日期.