ASP.NET图片防盗链


网站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" />


最后结果会显示


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值