使用HttpModules 来限制IP地址的访问

使用HttpModules 来限制IP地址的访问
原文出处:
http://www.codeproject.com/KB/aspnet/http-module-ip-security.aspx

示例代码下载:

下载文件 点击下载此文件


因为文章看起来比较容易,我就不翻译了。把核心的东西分享出来就行吧




1.先在web.config里面进行设置


    
        
            
        

    




2.使用下面这个方法



///
/// HTTP module to restrict access by IP address
///

public class SecurityHttpModule : IHttpModule
{
public SecurityHttpModule() { }

    public void Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(Application_BeginRequest);
    }

    private void Application_BeginRequest(object source, EventArgs e)
    {
        HttpContext context = ((HttpApplication)source).Context;
        string ipAddress = context.Request.UserHostAddress;
        if (!IsValidIpAddress(ipAddress))
        {
            context.Response.StatusCode = 403;  // (Forbidden)
        }
    }

    private bool IsValidIpAddress(string ipAddress)
    {
        return (ipAddress == "127.0.0.1");
    }

    public void Dispose() { /* clean up */ }
}





其它:把IP段做成数据集就可以大批量限制了。换成IP段也可以的吧。呵呵。




评论: 0 | 引用: 0 | 查看次数: 5620
发表评论
昵 称:
密 码: 游客发言不需要密码.
邮 箱: 邮件地址支持Gravatar头像,邮箱地址不会公开.
网 址: 输入网址便于回访.
内 容:
验证码:
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.
字数限制 30 字 | UBB代码 关闭 | [img]标签 关闭