2.自定义Handler.专用于处理图片请求.此handler做这么几件事,
1.获得图片请求的key,即上段代码中的encryptedEncoding.没有图片key,那就哪里来送回哪里去.(友好点.给个性感图片送过去..)
2.应该所有key都经过对称算法加密,so..解密先..
3.判断请求是否来自本站.是本站流程进4. 否则进5
4.本站请求再做进一步筛选.查看ShareData中是否有包含此key.(ShareData是自定义的.),存在图片的key那么清除ShareData中此key然后正确返回请求图片.不存在那么同步骤1一样送回去..(做ShareData判断是防止javascript 篡改request head信息)
5.不是来自本站的请求.可以提供自己的策略..我这里做的是30天链接过期.(因为第一段代码中用时间刻度做加密..所以这里解密了很好判断)
ImageHandler
public void ProcessRequest(HttpContext context)
{
HttpResponse response = context.Response;
HttpRequest request = context.Request;
string imgKey = request.QueryString["key"];
byte[] data = Convert.FromBase64String(imgKey);
string decryptedKey = SymmetricEncryptionUtility
.DecryptData
(
data,
ShareData.SymmetricKeyFile
);
//如果没有图片密钥就返回
if (imgKey == null) return;
string imagePath = null;
//检查请求是否来自外站
if (request.UrlReferrer != null)
{
if (String.Compare(
request.Url.Host,
request.UrlReferrer.Host,
true,
CultureInfo.InvariantCulture) == 0)
{
if (!ShareData.KeyCollections.Contains(imgKey))
return;
imagePath = request.PhysicalPath;
if (!File.Exists(imagePath))
{
response.StatusCode = 404;
return;
}
}
}
else//不是本站.检查明文时间轴
{
long ticks;
if (long.TryParse(decryptedKey, out ticks))
{
TimeSpan ts = new TimeSpan
(
DateTime.Now.Ticks - ticks
);
//如果大于一个月
if (ts.TotalDays > 30)
{
//输出链接过期
return;
}
}
}
//移除共享数据中key
ShareData.KeyCollections.Remove(decryptedKey);
response.ContentType = "image/"
+ Path.GetExtension(imagePath).ToLower();
response.WriteFile(imagePath);
}
public void ProcessRequest(HttpContext context)
{
HttpResponse response = context.Response;
HttpRequest request = context.Request;
string imgKey = request.QueryString["key"];
byte[] data = Convert.FromBase64String(imgKey);
string decryptedKey = SymmetricEncryptionUtility
.DecryptData
(
data,
ShareData.SymmetricKeyFile
);
//如果没有图片密钥就返回
if (imgKey == null) return;
string imagePath = null;
//检查请求是否来自外站
if (request.UrlReferrer != null)
{
if (String.Compare(
request.Url.Host,
request.UrlReferrer.Host,
true,
CultureInfo.InvariantCulture) == 0)
{
if (!ShareData.KeyCollections.Contains(imgKey))
return;
imagePath = request.PhysicalPath;
if (!File.Exists(imagePath))
{
response.StatusCode = 404;
return;
}
}
}
else//不是本站.检查明文时间轴
{
long ticks;
if (long.TryParse(decryptedKey, out ticks))
{
TimeSpan ts = new TimeSpan
(
DateTime.Now.Ticks - ticks
);
//如果大于一个月
if (ts.TotalDays > 30)
{
//输出链接过期
return;
}
}
}
//移除共享数据中key
ShareData.KeyCollections.Remove(decryptedKey);
response.ContentType = "image/"
+ Path.GetExtension(imagePath).ToLower();
response.WriteFile(imagePath);
}