Fork me on GitHub

Asp.net MVC3中全局图片防盗链


怎么样在Asp.Net MVC3中做到全局图片防盗链?如果熟悉Asp.Net的页面生命周期,相信解决这个问题应该很容易。下面就演示一下如何去做?

一、首先是全局的,我们肯定要在Global.asax文件中动手脚。一般在一个项目中所有的图片都会放在同一个文件夹中images,也就是说我们只要在刚开始发送请求的时候获取到url。

  1、刚开始请求,就要注册事件:Application_BeginRequest

  2、如果url中包含有images/,那么就判断当前请求与上次请求的端口号及域名是否相同,如果不相同的话则认为是盗链图片。

  3、代码如下:  

     /// <summary>
       /// 开始请求的事件
        /// </summary>
        protected void Application_BeginRequest()
        {
            //判断请求的路径中是否含有images/
            if (Request.RawUrl.ToLower().Contains("images/"))
            {
                Uri currentUrl = Request.Url;//当前的请求
                   Uri beforeUrl = Request.UrlReferrer;//上一次的请求
                   string path = Server.MapPath("../2.jpg");//盗链图片
                  if (beforeUrl != null)
                {
                    if (IsSameDomain(currentUrl, beforeUrl))
                    {
                        //输出当前请求的图片
                        path = Server.MapPath(Request.RawUrl);
                    }
                }
                //输入盗链图片
                   Response.ContentType = "image/jpg";
                Response.WriteFile(path);
                Response.End();
            }
        }
        /// <summary>
        /// 比较两次的域名和端口号是否相同
         /// </summary>
        /// <param name="url1"></param>
        /// <param name="url2"></param>
        /// <returns></returns>
        private bool IsSameDomain(Uri url1, Uri url2)
        {
            return Uri.Compare(url1, url2, UriComponents.HostAndPort, UriFormat.SafeUnescaped,
                            StringComparison.CurrentCultureIgnoreCase) == 0;
        }

二、同样屏蔽IP的时候也可以使用此种方法。

posted @ 2013-08-13 15:13  迁梦余光  阅读(954)  评论(0编辑  收藏  举报