我正在尝试写一个关于“防止图像窃取”的演示,参考资源: http: //www.mikesdotnetting.com/article/126/asp-net-mvc-prevent-image-leeching-with-a-custom-routehandler
但是当我使用时<img src="~/graphics/a.png" />
,ImageRouteHandler.cs 将不起作用。不幸的是,这个 ImageRouteHandler.cs 还不能工作。为什么 ??
public class ImageRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return new ImageHandler(requestContext);
}
}
public class ImageHandler : IHttpHandler
{
public ImageHandler(RequestContext context)
{
ProcessRequest(context);
}
private static void ProcessRequest(RequestContext requestContext)
{
var response = requestContext.HttpContext.Response;
var request = requestContext.HttpContext.Request;
var server = requestContext.HttpContext.Server;
var validRequestFile = requestContext.RouteData.Values["filename"].ToString();
const string invalidRequestFile = "thief.png";
var path = server.MapPath("~/graphics/");
response.Clear();
response.ContentType = GetContentType(request.Url.ToString());
if (request.ServerVariables["HTTP_REFERER"] != null &&
request.ServerVariables["HTTP_REFERER"].Contains("http://localhost:8010/")) //mikesdotnetting.com
{
response.TransmitFile(path + validRequestFile);
}
else
{
response.TransmitFile(path + invalidRequestFile);
}
response.End();
}
private static string GetContentType(string url)
{
switch (Path.GetExtension(url))
{
case ".gif":
return "Image/gif";
case ".jpg":
return "Image/jpeg";
case ".png":
return "Image/png";
default:
break;
}
return null;
}
public bool IsReusable
{
get
{
return true;
}
}
public void ProcessRequest(HttpContext context)
{
throw new NotImplementedException();
}
}