当前位置: 移动技术网 > IT编程>开发语言>.net > asp.net中利用ashx实现图片防盗链代码

asp.net中利用ashx实现图片防盗链代码

2018年04月19日  | 移动技术网IT编程  | 我要评论

杨月楼传,窗帘布料,verypsp阅读权限

get /img.ashx?img=svn_work.gif http/1.1
accept: */*
referer: http://www.svnhost.cn/
accept-language: zh-cn
ua-cpu: x86
accept-encoding: gzip, deflate
user-agent: mozilla/4.0 (compatible; msie 7.0; windows nt 5.2; .net clr 1.1.4322; .net clr 2.0.50727; .net clr 3.0.04506.648; .net clr 3.5.21022; ciba)
host: www.svnhost.cn
connection: keep-alive
该数据包表示请求http://www.svnhost.cn/img.ashx?img=svn_work.gif文件。我们可以看到referer表示上一页请求页面地址,也就是文件来源。host表示当前请求的主机地址。
下面是一个盗链的数据包
get /img.ashx?img=svn_work.gif http/1.1
accept: */*
referer: http://745.cc/
accept-language: zh-cn
ua-cpu: x86
accept-encoding: gzip, deflate
user-agent: mozilla/4.0 (compatible; msie 7.0; windows nt 5.2; .net clr 1.1.4322; .net clr 2.0.50727; .net clr 3.0.04506.648; .net clr 3.5.21022; ciba)
host: www.svnhost.cn
connection: keep-alive
我们可以看到,上面两个数据,表示对于同一个文件:http://www.corange.cn/img.ashx?img=svn_work.gif的请求过程,这里的不同就是referer,也就是都是请求同一个文件,但是请求的来源是不同的。因此我们可以在程序里判断是否是来源于当前服务器,来判断是否是盗链。明白原理以后,实现防盗链就非常简单了。下面以图片防盗链来实现一个演示。asp.net中添加一个img.ashx文件,然后后台代码如下:
复制代码 代码如下:

using system;
using system.collections;
using system.data;
using system.web;
using system.web.services;
using system.web.services.protocols;
namespace getimage
{
/// <summary>
/// $codebehindclassname$ 的摘要说明
/// </summary>
[webservice(namespace = "http://tempuri.org/")]
[webservicebinding(conformsto = wsiprofiles.basicprofile1_1)]
public class img : ihttphandler
{
public void processrequest(httpcontext context)
{
context.response.contenttype = "image/jpg";
if (context.request.urlreferrer != null && context.request.urlreferrer.host.equals(context.request.url.host, stringcomparison.invariantcultureignorecase))
context.response.writefile(context.server.mappath("~/" + context.request.querystring["img"]));
else
context.response.writefile(context.server.mappath("~/logo.gif"));
}
public bool isreusable
{
get
{
return false;
}
}
}
}

表示如果来源不为空,并且来源的服务器和当前服务器一致,那就表示是正常访问,非盗链。正常访问文件内容。
否则就是盗链,返回网站logo。
你甚至可以做成随机返回正确的图片,随机返回错误图片,或者定时返回正确图片,定时返回错误图片。
然后就是图片的使用了,这时使用图片就不是直接<input type="image" src="svn_work.gif" />了,而是<input type="image" src="/img.ashx?img=svn_work.gif" />,就是说通过img,ashx来读取图片。别人盗链的话要用下面代码:<input type="image" src="http://www.corange.cn/img.ashx?img=svn_work.gif" />。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网