2014-10-09 50 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