views:

359

answers:

2

I am using asp.net pagemethods with jquery.... How to get the value of a session variable inside static method in c#...

    protected void Page_Load(object sender, EventArgs e)
    {
        Session["UserName"] = "Pandiya";
    }
    [WebMethod]
    public static string GetName()
    {
        string s = Session["UserName"].ToString();
        return s;
    }

when i compile this i get the error An object reference is required for the non-static field, method, or property 'System.Web.UI.Page.Session.get' Any suggestion or any alternative...

+1  A: 

HttpContext.Current.Session["..."]

HttpContext.Current gets you the current ... well, Http Context; from which you can access: Session, Request, Response etc

jwwishart
@jwwishart ya it worked... But why is it so?
Pandiya Chendur
HttpContext.Current gives you access to the current Http Context as explained in the edit i just did. The HttpContext.Current property is static (http://msdn.microsoft.com/en-us/library/system.web.httpcontext_members.aspx) and it does it's magic and returns you the current HttpContext. You should have access to most of the stuff you have access in the code behind etc.
jwwishart
P.S. You were trying to access a non-static property (Session property) via a static method... obviously it(the Session property) exists only on an instance of the class! Hope this explains things better?
jwwishart
@Pandiya Chendur: `Session` is a instance property of the Page class that returns an `HttpSessionState` object. When you write something like `Session["..."]`, this is really `this.Session["..."]`. Because a static member has no `this` object, you can't access the `Session` property. You can, however, access the same `HttpSessionState` object using the code that hwwishart suggested.
P Daddy
@jwwishart: Sorry for mistyping your name in the previous comment. J and H are right next to each other and the room is dark at the moment.
P Daddy
@P Daddy - No problems and nice explanation +1
jwwishart
+2  A: 

If you haven't changed thread, you can use HttpContext.Current.Session, as indicated by jwwishart.

HttpContext.Current returns the context associated with the thread. Obviously this means you can't use it if you've started a new thread, for example. You may also need to consider thread agility - ASP.NET requests don't always execute on the same thread for the whole of the request. I believe that the context is propagated appropriately, but it's something to bear in mind.

On the other hand, I'm not sure whether you'll even have a session for an AJAX Page Method. You can try it, but I'd be somewhat nervous of it. Ideally you should pass all the information you need from the client instead.

Jon Skeet