Count Image Requests from a Web Server using ASP.NET

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

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:

using System;
using System.Web;
public class JpgHandler : IHttpHandler
{

public void ProcessRequest(HttpContext context)
{
string FileName = context.Server.MapPath(context.Request.FilePath);
if (context.Request.ServerVariables["HTTP_REFERER"] == null)
{
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile("/no.jpg");
}
else
{
if (context.Request.ServerVariables["HTTP_REFERER"].ToLower().IndexOf("dotnetheaven.com") > 0 )
{
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile(FileName);
}
else
{
context.Response.ContentType = "image/JPEG";
context.Response.WriteFile("/no.jpg");
}
}
}

public bool IsReusable
{
get
{ return true; }
}
}

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.