How to Stop Leeching in ASP.Net

4/12/2008

I'm certain that this issue has come up with a web site you've been working on, but how can you stop people from leeching your content? Text is a bit difficult, I mean there really isn't any way to stop someone from doing a screen scrape of your site. Effectively anyway. Images and JavaScript on the other hand are a bit easier. All that is required is one simple HTTP Module:

   1: using System;
   2: using System.Web; 
   3:  
   4: namespace Site.HTTPModules
   5: {
   6:     public class AntiLeech:IHttpModule
   7:     {
   8:         public void Dispose()
   9:         { 
  10:     
  11:         }
  12:     
  13:         public void Init(HttpApplication context)
  14:         {
  15:             context.BeginRequest += new EventHandler(context_BeginRequest);
  16:         } 
  17:  
  18:         void context_BeginRequest(object sender, EventArgs e)
  19:         {
  20:             if(((HttpApplication)sender).Context.Request.UrlReferrer.Host !=((HttpApplication)sender).Context.Request.Url.Host)
  21:             {
  22:                 ((HttpApplication)sender).Context.Response.Status="Thanks for leeching";
  23:                 ((HttpApplication)sender).Context.Response.StatusCode=401;
  24:                 ((HttpApplication)sender).Context.Response.End();
  25:             }
  26:         }
  27:     }
  28: }

All this code does, is checks the referring host of the request being made and if it is not the same as the host for the file requested, it returns a 401 unauthorized code along with a nice little message. This, however, can cause issues if people are using software to translate your site so you may want to keep a list of files you think are being leeched and only block those.

Now you may try compiling that code into your website and you'll notice that it doesn't work. This is because you haven't added the module to the web.config file yet. All you need to do is find the httpModules section and add in the following line:

   1: <add name="AntiLeech" type="Site.HttpModules.AntiLeech,Site"/> 

Where Site is the default namespace for your site. You'll also need to change the namespace of the c# code above. 

You could of course modify this code so that certain locations/hosts can view your content, certain files/file types can pass through without any issues, etc. But the code above should get you started. So look at the code, leave feedback, and happy coding.



Comments