CREATE TABLE IPAllowList (
IP varchar(15) PRIMARY KEY,
Description nvarchar(100),
CreatedDate datetime DEFAULT GETDATE()
);
public partial class Admin_IP : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
Server.Execute("chklog.aspx"); // 權限檢查
}
protected void btnAdd_Click(object sender, EventArgs e) {
string ip = txtIP.Text.Trim();
if (IsValidIP(ip)) {
using (SqlConnection conn = new SqlConnection(connStr)) {
string sql = "INSERT INTO IPAllowList (IP, Description) VALUES (@ip, @desc)";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@ip", ip);
cmd.Parameters.AddWithValue("@desc", txtDesc.Text.Trim());
conn.Open();
cmd.ExecuteNonQuery();
}
lbIP.DataBind(); // 重新繫結
}
}
protected void lbDelete_Click(object sender, EventArgs e) {
if (lbIP.SelectedItem != null) {
string ip = lbIP.SelectedValue;
using (SqlConnection conn = new SqlConnection(connStr)) {
string sql = "DELETE FROM IPAllowList WHERE IP=@ip";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@ip", ip);
conn.Open();
cmd.ExecuteNonQuery();
}
lbIP.DataBind();
}
}
private bool IsValidIP(string ip) {
// 簡易驗證,實際建議用 IPAddress.TryParse
return System.Net.IPAddress.TryParse(ip, out _);
}
}
在 `Global.asax` 或 `HttpModule` 中攔截所有請求:
public class IPFilterModule : IHttpModule {
public void Init(HttpApplication context) {
context.BeginRequest += OnBeginRequest;
}
void OnBeginRequest(object sender, EventArgs e) {
HttpApplication app = (HttpApplication)sender;
string clientIP = GetClientIP(app.Request);
if (!IsIPAllowed(clientIP)) {
app.Response.StatusCode = 403;
app.Response.Write("您的 IP 未被授權存取");
app.Response.End();
}
}
string GetClientIP(HttpRequest req) {
string ip = req.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ip))
ip = req.ServerVariables["REMOTE_ADDR"];
return ip.Split(',')[0].Trim(); // 取第一個 Proxy IP
}
bool IsIPAllowed(string ip) {
// 從快取讀取白名單,避免每請求查資料庫
var list = HttpRuntime.Cache["IPAllowList"] as List<string>;
if (list == null) {
list = LoadFromDB();
HttpRuntime.Cache.Insert("IPAllowList", list, null,
DateTime.Now.AddMinutes(10), Cache.NoSlidingExpiration);
}
return list.Contains(ip);
}
}
在 `web.config` 註冊模組:
<system.webServer>
<modules>
<add name="IPFilter" type="MyNamespace.IPFilterModule" />
</modules>
</system.webServer>