You can get the link to the page through HttpContext.CurrentHandler . But since Control.ViewState is protected , you cannot access it (without using reflection), unlike Session , accessible through HttpContext.Current.Session .
Thus, either do not use the static method, use Session , or use this approach:
public static string CustomerId { get { return (string)GetCurrentPageViewState()["CustomerId"]; } set { GetCurrentPageViewState()["CustomerId"] = value; } } public static System.Web.UI.StateBag GetCurrentPageViewState() { Page page = HttpContext.Current.Handler as Page; var viewStateProp = page?.GetType().GetProperty("ViewState", BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.NonPublic); return (System.Web.UI.StateBag) viewStateProp?.GetValue(page); }
However, this will not work if called through a WebService, because then it is outside the Page-Lifecycle .
Tim schmelter
source share