萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET IP 存取控制:資料庫驗證與後台管理完整實作

資料庫設計

CREATE TABLE IPAllowList (
  IP varchar(15) PRIMARY KEY,
  Description nvarchar(100),
  CreatedDate datetime DEFAULT GETDATE()
);

後台管理頁面

ASPX 重點

  • `SqlDataSource` 綁定 `ListBox` 顯示現有 IP
  • `RegularExpressionValidator` 驗證 IPv4 格式:`^(\d{1,3}\.){3}\d{1,3}$`(需再檢查各段 0-255)
  • 新增/刪除按鈕觸發後端邏輯

代碼後置

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>

關鍵優化

  • 白名單快取 10 分鐘,減少 DB 壓力
  • 支援 `X-Forwarded-For` 取得真實客戶端 IP(反向 Proxy 環境)
  • 模組化設計,不侵入業務頁面
  • 參數化查詢防 SQL Injection
copyright © 萬盛學電腦網 all rights reserved