Go homepage(回首页) Upload pictures (上传图片) Write articles (发文字帖)
The author:(作者)delvpublished in(发表于) 2014/1/10 6:30:54 图片、文件防盗链程序_[Asp.Net教程]
1private void Application_BeginRequest(Object source, EventArgs e) 2{ 3 HttpApplication application = (HttpApplication)source; 4 HttpContext context = application.Context; 5 bool isSafe = true; //是否合法链接 6 string uri = context.Request.Url.AbsolutePath.ToLower(); 7 if (uri.LastIndexOf(".") > 0 && context.Request.UrlReferrer != null) 8 { 9 string exp = uri.Substring(uri.LastIndexOf("."));10 //这里是判断文件后缀名是否在排除的文件类型列表之内11 bool isHas = ClassLibrary.RData.RString.StrIsIncUseSC(exp, config.ImgSafeType.Split('|'));12 if (isHas)13 {14 string domainOutter = context.Request.UrlReferrer.Authority.ToLower(); //包含域名和端口15 ArrayList arry = Common.Cache.GetDomainValid();//取系统定义的合法的域名绑定列表16 isSafe = arry.Contains(domainOutter); //判断当前请求的域名是否在合法列表之内17 }18 }19 //下面就是不合法的时候的输出了,如果有默认替代图片则输出,如果没有就生成一个,格式为.gif20 if (!isSafe)21 {22 Bitmap img = null;23 Graphics g = null;24 MemoryStream ms = null;2526 try27 {28 string picPath = ClassLibrary.RPath.GetFullDirectory("images/unlawful.gif");29 if (File.Exists(picPath))30 {31 img = new Bitmap(picPath, false);32 }33 else34 {35 img = new Bitmap(64, 64);36 g = Graphics.FromImage(img);37 g.Clear(Color.White);38 Font f = new Font("宋体,黑体,Arial", 9,FontStyle.Bold);39 SolidBrush s = new SolidBrush(Color.Red);40 g.DrawString(Resources.Message.LawlessLink, f, s, 1, 20);41 img.Save(picPath, ImageFormat.Gif);42 }43 ms = new MemoryStream();44 img.Save(ms, ImageFormat.Gif);45 context.Response.ClearContent();46 context.Response.ContentType = "image/Gif";47 context.Response.BinaryWrite(ms.ToArray());48 context.Response.End();49 }50 catch51 { }52 finally53 {54 if(g != null )55 g.Dispose();56 img.Dispose();57 }58 }59} 凡是有利必有害,这样做最大的缺点就是增加了系统开销,客户端的每一请求都要过滤一遍,性能自然要打折扣了。不知道哪位朋友有更好的办法,或者优化的方法,一起来探讨探讨。
http://www.cnblogs.com/nowind/archive/2007/01/16/622016.html
赞