Subscribe to our RSS feed!

ASP.NET - Blocking External Referrers

I was ones faced with the issue of enforcing copyright on different files on a website.

That meant that images and dynamically created XML files had to be blocked if accessed from outside the website.

So, I had to find a way to prevent other websites from linking to or referencing these files. Copyright or not, it is a good idea to do it on dynamically created files such as charts, because they take a lot of computer power to generate.

That resulted in an HttpModule that stops all requests coming from outside the website to a custom list of files.

If your images are inserted into a <img> tag on another domain, they will be blocked.

The list can use wildcards so you can stop all files of a certain type as well. It could look like this *.gif|*.jpg|image.ashx.

Below are the two methods of the module that stops the illegal requests.

private void context_BeginRequest(object sender, EventArgs e)
  HttpContext context = ((HttpApplication)sender).Context;
  // Do nothing if the request is legal
  if (ReguestIsLegal(context))

  // Accessed directly
  if (context.Request.UrlReferrer == null)
   context.Response.Write("Access denied");

  // Linked to or embedded into another domain
  if (context.Request.UrlReferrer.Host != context.Request.Url.Host)
   context.Response.Write("Access denied");

private bool ReguestIsLegal(HttpContext context)
  string mappings = ConfigurationManager.AppSettings["BlockMapping"];
  string fileName = context.Request.PhysicalPath;

  foreach (string map in mappings.Split('|'))
   string cleaned = map.Replace("*", ".*").Replace(".", ".");
   if (Regex.IsMatch(fileName, cleaned, RegexOptions.IgnoreCase))
    return false;

return true;

The method RequestIsLegal uses regular expressions to determine if the requested file matches the mappings in the web.config.


Download the ExternalAccessModule.cs below and add put it in the App_Code folder. Then add the following lines to the web.config's section.

  <add type="ExternalAccessModule" name="ExternalAccessModule"/>

And last, add the mappings to the AppSettings of the web.config. Modify it to match your own files.

<add key="BlockMapping" value="*.gif|*.jpg|image.ashx"/>

Download (,85 KB)



Add to | Digg | Reddit | Furl

Bookmark and Share

About the author:
Mads Kristensen currently works as a Senior Developer at Traceworks located in Copenhagen, Denmark. Mads graduated from Copenhagen Technical Academy with a multimedia degree in 2003, but has been a professional developer since 2000. His main focus is on ASP.NET but is responsible for Winforms, Windows- and web services in his daily work as well. A true .NET developer with great passion for the simple solution.
Get Your Site Submitted for Free in the World's Largest B2B Directory!

*Mandatory Field
* *

ASP NET Blocking External Referrers