网站A是有图片的网站;网站B要通过盗链来获取图片展现给用户。
如何防止盗链
在网站A ,定义一个类,就叫 Image保护.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
///Image保护 的摘要说明
/// </summary>
public class Image保护:IHttpHandler
{
public Image保护()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
#region IHttpHandler 成员
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
string fileName = context.Server.MapPath(context.Request.FilePath);
if (context.Request.UrlReferrer.Host==null)
{
context.Request.ContentType = "image/JPEG";
context.Response.WriteFile("~/error.gif");
}
else
{
if (context.Request.UrlReferrer.ToString().IndexOf("ASP.NET_高级_本网站图片保护") > -1)//也可判断主机名是否相同;但是因为在一台电脑上测试,主机名是一样的,所以就用网站的根目录进行测试了。
{
context.Request.ContentType = "image/JPEG";
context.Response.WriteFile(fileName);
}
else
{
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile("~/error.gif");
}
}
}
#endregion
}
然后在Web.config的system.web节点下添加
<httpHandlers>
<add verb="*" path="images/*.jpg" type="Image保护,App_Code"/>
</httpHandlers>
网站B 盗链网站A的图片
<asp:Image ID="Image1" runat="server" ImageUrl="http://localhost:2196/ASP.NET_高级_本网站图片保护/images/caocao.jpg" />
最后结果会显示