首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

ASP.NET 判斷 Session 是否有效的優雅寫法:Func 委派與 Null 條件運算子

     編輯:ASP.NET 基礎

傳統寫法的痛點

if (Session["UserID"] == null || Session["UserID"].ToString() == "")
    Response.Redirect("Login.aspx");

重複、易寫錯、若 Session 物件本身為 null 會拋出例外(極少見但理論上可能)。

現代優雅寫法:Func + ?? 運算子

// 定義於共用工具類別
public static Func IsLogin = obj => obj as string ?? string.Empty;

使用方式

if (string.IsNullOrEmpty(IsLogin(Session["UserID"])))
    Response.Redirect("Login.aspx?msg=登入逾時");

進階:儲存自訂物件 (UserInfo)

public class UserInfo { public int UserId; public string Name; public string Role; }

public static Func GetUser = obj => obj as UserInfo ?? new UserInfo { UserId = -1 };

呼叫端

UserInfo user = GetUser(Session["CurrentUser"]);
if (user.UserId == -1) Response.Redirect("Login.aspx");

// 直接使用強型別物件
lblWelcome.Text = "歡迎," + user.Name;

為什麼不直接用 string.IsNullOrEmpty(Session["UserID"] as string)?

若 Session 中**完全不存在該 Key**,Session["UserID"] 回傳 null,as string 結果為 null,`IsNullOrEmpty` 可正常處理。**但若 Session 物件本身為 null**(極罕見,如 Session 模式切換瞬間),直接存取會拋出 NullReferenceException。Func 封裝可集中防禦。

更完整的驗證模式:BasePage + 模型繫結

public abstract class SecurePage : Page
{
    protected UserInfo CurrentUser { get; private set; }

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        CurrentUser = Session["CurrentUser"] as UserInfo;
        if (CurrentUser == null) Response.Redirect("~/Login.aspx?ReturnUrl=" + Server.UrlEncode(Request.RawUrl));
    }
}

業務頁面繼承 SecurePage 即自動擁有 CurrentUser 強型別屬性,編譯期檢查、IntelliSense 完整支援。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved