Wednesday, March 28, 2012

PageMethods (which are static) and access Session from them ?

Since PageMethods are static if I need the access to the Session how should I go about it ?.

One straightforward way may be to add a field in my (Page) class like this

public partialclass MyPage : Page {private static MyPage _p;protected void Page_Load(object sender, EventArgs e){ _p =this; } [ScriptMethod][WebMethod]public static void MyPageMethod(string contextKey){int a = (int)_p.Request.Session["myintval"]; } }
Do you guys thinking this is the only and best way to do it ?.
Please suggest.

Regards & thanks


you could do it in more simple way:

instead of

int a = (int)_p.Request.Session["myintval"];

int a = (int) HttpContext.Current.Session["myintval"];

The static property Current of HttpContext is accessible from everywhere.



An even better solution would be to implement a facade pattern for your session (more infohere).

Regardless of anything else you do in terms of code style and whatnot, you have to change your WebMethodAttribute to


silly me, huh. I knew I was doing something wrong.

Thanks for the answer Yani



No comments:

Post a Comment