创建CustomHandler.JpgHandler
public class JpgHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
try
{
// 获取文件服务器端物理路径
string FileName = context.Server.MapPath(context.Request.FilePath);
// 如果UrlReferrer为空,则显示一张默认的禁止盗链的图片
if (context.Request.UrlReferrer.Host == null)
{
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile("/error.jpg");
}
else
{
// 如果 UrlReferrer中不包含自己站点主机域名,则显示一张默认的禁止盗链的图片
if ((context.Request.UrlReferrer.Host.Contains("localhost")))
{
context.Response.ContentType = "application/pdf";
context.Response.WriteFile(FileName);
}
else
{
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile("/error.jpg");
}
}
}
catch (Exception ex)
{
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile("/error.jpg");
}
}
public bool IsReusable
{
get { return true; }
}
}
在项目中引用该编译好的dll文件,并在项目中注册该handler
<system.webServer>
<handlers>
<add name="myjpghandler" path="*.jpg" verb="*" type="CustomHandler.JpgHandler, CustomHandler" />
</handlers>
</system.webServer>
本文来自:http://www.cnblogs.com/sssleon/p/5168051.html