2014-10-09 53 views
0

有没有办法在ASP.NET/IIS 7中检测热链接图像视图? 我不想阻止观看者,当某人在Google图片搜索中点击我的图片时,我只需要为每个静态图片增加图片浏览次数计数器。ASP.NET检测热链接图像视图

+0

热点链接图片视图与查看您网站上图片的用户有何不同? – MikeSmithDev 2014-10-13 21:57:48

+0

热链接只请求图片文件,而不是整个网页。 – 2014-10-14 09:32:24

回答

2

这很简单。您只需检查Referrer请求标头,并记录与本地域不匹配的请求。像这样的东西应该工作:

using System; 
using System.Linq; 
using System.Web; 

namespace ImageLogger 
{ 
    public class ImageLoggerModule : IHttpModule 
    { 
     public void Init(HttpApplication context) 
     { 
      context.LogRequest += new EventHandler(context_LogRequest); 
     } 

     void context_LogRequest(object sender, EventArgs e) 
     { 
      var context = HttpContext.Current; 

      // perhaps you have a better way to check if the file needs logging, 
      // e.g.: it is a file in a certain folder 
      switch (context.Request.Url.AbsolutePath.Split('.').Last().ToLower()) 
      { 
       case "png": 
       case "jpg": 
       case "gif": 
       case "bmp": 
        if (context.Request.UrlReferrer != null) 
        { 
         if (!"localhost".Equals(
          context.Request.UrlReferrer.Host, 
          StringComparison.CurrentCultureIgnoreCase) 
          ) 
         { 
          // request is not from local domain --> log request 
         } 
        } 
        break; 
      } 
     } 

     public void Dispose() 
     { 
     } 
    } 
} 

在您链接此模块中的模块部分的web.config:

<system.webServer> 
    <modules> 
     <add name="ImageLogger" type="ImageLogger.ImageLoggerModule"/> 

在集成模式下这只能在IIS中 - 在经典模式ASP.NET从未获取静态文件的任何事件。

现在我想起它;你可以完全取消当前的日志记录(在页面中,我猜?),并使用这个模块,并摆脱引用逻辑。这样,你只有一个地方可以进行日志记录。

+0

谢谢!它的工作原理,但我必须做更多的日志记录筛选,因为有太多的数据库查询,它会减缓图像加载,也许更新日志在一个单独的线程? – 2014-10-20 21:46:41