开发者

Using an HttpModule with Application_BeginRequest, how do I check only the first request?

I'm using the following HttpModule to stop a couple of IPs that constantly attempt to spam my contact form. I don't get the spam as they trigger System.Web.HttpRequestValidationException but I do get the Exception report in my email inbox. It's not quite as annoying but almost.

I eventually want to test against either a list of IPs from the database or maybe implement the HttpBL api to test against known blacklisted IPs but doing this on every request seems to be overkill. Either way I do it, whether using IPs in the database or making requests to an external blacklist at every page request surely seems unnecessary. Can you point me in the direction of checking this once and if the IP passes the test the first time to stop checking?

using System;
using System.Web;

namespace DomainModel.Services
{
    public class BlockIPModule : IHttpModule
    {
        public void Dispose() {}

        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(Application_BeginRequest);
        }
开发者_如何学Python
        private void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext context = ((HttpApplication)sender).Context;
            string currentIP = context.Request.UserHostAddress;
            if (!IsIpValid(currentIP))
            {
                context.Response.StatusCode = 403; 
            }
        }

        private bool IsIpValid(string checkIP)
        {
            return (checkIP != "213.5.70.205" && checkIP != "188.92.75.82");
        }

    }
}

updated code removed - terrible idea.


HTTP is stateless, and therefore, you really do have to check each request. You could cache the blacklist of IP addresses so you don't have to load it each time, but you'll still need to always run some test.

If you have control over it, the other option would be to do some filtering on your router. That would free your code from having to do it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜