您的位置:首页 > 编程语言 > ASP

.NET:在ASP.NET中如何进行IP限制

2013-05-05 08:37 489 查看

背景

为了增强系统的安全,很多信息系统都提供了“IP限制”功能。功能虽然简单,但是从业五年来从来没有是实现过,因此就以博文的形式记录下来。

思路

实现应该很简答,功能可以分解为如下这三个问题:

判断当前请求是否应用IP限制,有些请求不用应用IP限制的。

当前客户IP是否包含在限制列表中。

如何以AOP的形式应用IP限制



1和2可以抽象为一个接口

using System;

namespace IpLimit.Codes
{
interface IIpLimitService
{
bool IsInExcludeUrl(string url);
bool IsInLimit(string ip);
}
}


3可以用IHttpModule实现

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace IpLimit.Codes
{
public sealed class IpLimitModule : IHttpModule
{
public void Dispose()
{

}

public void Init(HttpApplication context)
{
context.BeginRequest += this.OnBeginRequest;
}

private void OnBeginRequest(object sender, EventArgs args)
{
var ipLimitService = new IpLimitService();
var clientIp = HttpContext.Current.Request.UserHostAddress;
var requestUrl = HttpContext.Current.Request.Url;

if (ipLimitService.IsInExcludeUrl(requestUrl.AbsolutePath))
{
return;
}

if (ipLimitService.IsInLimit(clientIp))
{
HttpContext.Current.Response.Redirect("IpLimit.html");
}
}
}
}


实现细节

this.Request.UserHostAddress的格式为“127.0.0.1”。

this.Request.Url.AbsolutePath的格式为“/Tests/GetIp.aspx”,

具体限制IP列表和排除地址列表的存储可以自己酌情实现。

备注

对应黑客知识,我并不了解,黑客是不是很容易模拟客户端IP,有高手的话,请指点一二。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: