Count Image Requests from a Web Server using ASP.NET (VB.Net)

Description

This article explains you how we can count Image request from a
Web server using C# and ASP.NET.

In an ASP.NET application, global.asax is the place where we can see each request for the application by using Application_BeginRequest event. What if we want to keep track of image requests?

Web
server maintains a server log file where we can see each and every request to web server. But if we want to make a web interface to see the requests then we need to do some extra work.

As we know there aspnet_isapi dll, which takes care of each request. By default, we can't see image file entries in IIS -> home directory -> configuration -> mapping so to collect those type of requests we need to add that mapping to IIS -> home directory -> configuration -> mapping.

After successfully addition we can make our httphandler to handle image requests processed by aspnet_isapi.dll. We can make class inherited by IHttpHandler class where we can collect those image requests.

Example:
  

Imports System
Imports System.Web
Public Class JpgHandler : Implements IHttpHandler

Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim FileName As String = context.Server.MapPath(context.Request.FilePath)
If context.Request.ServerVariables("HTTP_REFERER") Is Nothing Then
   context.Response.ContentType = "image/JPEG"
   context.Response.WriteFile("/no.jpg")
Else
   If context.Request.ServerVariables("HTTP_REFERER").ToLower().IndexOf("dotnetheaven.com") > 0 Then
      context.Response.ContentType = "image/JPEG"
      context.Response.WriteFile(FileName)
   Else
      context.Response.ContentType = "image/JPEG"
      context.Response.WriteFile("/no.jpg")
   End If
End
If
End
Sub

Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
   Return True
End
Get
End
Property
End
Class

After making this class we need to call it in web application.

To call in web application we need to add this in web.config:

<httpHandlers>
   <
add verb="*" path="*.jpg" type="JpgHandler, MyDll"/>
</
httpHandlers>

Now your application is ready to collect image requests. In above config settings, JpgHandler is class name and MyDll is the DLL name.

NOTE: THIS ARTICLE IS CONVERTED FROM C# TO VB.NET USING A CONVERSION TOOL. ORIGINAL ARTICLE CAN BE FOUND ON C# CORNER (WWW.C-SHARPCORNER.COM).


Similar Articles