我使用 ASP.NET
我需要为用户提供从服务器下载文件的临时链接。
它应该是一个临时链接(页面),可以在短时间内(例如 12 小时)使用。我如何生成此链接(或带有链接的临时网页)?
最佳答案
这是一个相当完整的示例。
首先是一个使用 secret 盐和到期时间创建短十六进制字符串的函数:
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);
}
然后是生成一周有效期链接的片段:
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);
如果提供了有效链接,最后是发送文件的下载页面:
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
}
您当然应该将其包装在一些异常处理中以捕获损坏的请求。
关于asp.net - 创建临时下载链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5703201/