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

在應用開發中實現對上下文(Context)資料的統一管理

     編輯:關於ASP.NET

ApplicationContext 組件

整合 HttpSessionState(Web)與 CallContext(GUI/服務)統一管理上下文資料(如當前用戶資訊、調用鏈路共享資料)。

核心代碼

[Serializable]
public class ApplicationContext : Dictionary<string, object>
{
    public const string ContextKey = "Artech.ApplicationContexts.ApplicationContext";

    public static ApplicationContext Current
    {
        get
        {
            if (HttpContext.Current != null)
            {
                if (HttpContext.Current.Session[ContextKey] == null)
                    HttpContext.Current.Session[ContextKey] = new ApplicationContext();
                return HttpContext.Current.Session[ContextKey] as ApplicationContext;
            }
            if (CallContext.GetData(ContextKey) == null)
                CallContext.SetData(ContextKey, new ApplicationContext());
            return CallContext.GetData(ContextKey) as ApplicationContext;
        }
    }
}

使用方式

// 寫入
ApplicationContext.Current["UserName"] = "Foo";
// 讀取
var userName = ApplicationContext.Current["UserName"];

鍵值固定為 Artech.ApplicationContexts.ApplicationContext。Web 環境自動使用 Session,非 Web 環境落回 CallContext(跨 AppDomain 需序列化,故標記 [Serializable])。

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