ASP.NET blog by Subgurim

Some things about ASP.NET, C#, ASP.NET AJAX, javascript...

AntiSpam HttpModule

I hate the Spam robots, and they hate me. I also hate captchas... so, how can I avoid that they write garbage on my websites?

This HttpModule, with three (1+2) basic rules (the last is optional) has been the solution:

using System;
using System.Web;

namespace Subgurim.Tools
{
    public class AntiSpamModule : IHttpModule
    {
        public void Init(HttpApplication app)
        {
            app.BeginRequest += new EventHandler(AntiSpamFilter);
        }

        private void AntiSpamFilter(object sender, EventArgs e)
        {
            HttpResponse response = ((HttpApplication)sender).Response;
            HttpRequest request = ((HttpApplication)sender).Request;

            // 1.- They are sending a  POST
            // 2.- The call doesn't provide from any other page
            // 3.- The call provides from another page but it's not on my domain.
            if ((request.Form.Count > 0) &&
                    ((request.UrlReferrer == null) ||
                    (!request.UrlReferrer.Authority.Equals(request.Url.Authority, StringComparison.InvariantCultureIgnoreCase))))
            {
                try
                {
                    response.End();
                }
                catch (System.Threading.ThreadAbortException ex)
                {
                    // No hacer nada
                }
            }
        }

        public void Dispose()
        {
        }
    }
}

Configure the HttpModule inside the system.web of your web.config and that's all.

    <system.web>
        <httpModules>
            <add name="AntiSpamModule" type="Subgurim.Tools.AntiSpamModule"/>
        </httpModules>
    </system.web>

Comments

rajbk said:

1) If the spammer finds out the technique you are using, they can easily defeat it.

2) Never rely on the UrlReferrer property. It can be disabled in, for example, Firefox. This means that a "good" user who has the url referrer property disabled will not be able to see you site.

Raj

# April 4, 2008 3:41 PM

Andre Tagesgeld said:

@rajbk: if the referrer is disabled, above method works like a charm (referrer != mydomain)...

But you can simply fake the referrer. So, finally, there is no perfect solution without a captcha.

# June 6, 2008 10:42 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)