A recent project in a government system requires configurable IP access control, since there is this demand we naturally have to meet.
For the previous article in the use of IHttpHandlerFactory authentication user experience, this time using HttpModule to detect users earlier.
How to better judge whether the IP in the Allowed list or banned list, based on the current IPV4, simply IP 4-bit field to judge separately, this can also be a simple batch of IP network settings.
The configuration is saved to the database in the system, and the database is designed as follows:
Next you can write HttpModule, as follows:
public class IPHttpModule : IHttpModule
{
#region IHttpModule 成员
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
}
#endregion
///
/// 提示信息
///
const string ErrorHtml = @"
您的访问受到限 制,请与系统管理员联系。
";
void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
HttpContext context = app.Context;
// 判断是否IP限制
if (!CheckPermisssion (context.Request.UserHostAddress))
{
context.Response.Write (ErrorHtml);
context.Response.End();
}
}
}