How to access an ASP.NET Session object inside a static function (error CS0120)

by APIJunkie 1/11/2008 11:18:00 AM

If you are trying to access an ASP.NET Session object from inside a static function you will encounter error CS0120:

"An object reference is required for non static field, method, or property... "

The problem is that the Session object is a non static member of the Page/Control class you are using.

When you are inside a static function you do not have access to non static members of your class.

Example:

// this function is ok inside a page or control

void testFunc()

{

  Session["test"] = "testString";

}

// this function will produce an error inside a page or control

static void testStaticFunc()

{

  Session[
"test"] = "testString";

}

The solution to the problem is to access the Session object from another static object/function that has access to the current Session object.

Enter  HttpContext.Current.Session -> http://msdn2.microsoft.com/en-us/library/system.web.httpcontext_members.aspx

The Session object obtained from HttpContext can be used from inside a static function since HttpContext.Current is a static property.

Here is an example of how to use it:

// this function is ok inside a page or control

static void testStaticFunc()

{

  HttpContext.Current.Session["test"] = "testString";

}

 

Currently rated 4.7 by 3 people

  • Currently 4.666667/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

ASP.NET | Session | Static

Comments

1/11/2008 12:09:21 PM

trackback

Trackback from DotNetKicks.com

How to access an ASP.NET Session object inside a static function (erro

DotNetKicks.com

2/15/2008 5:45:54 AM

Mike

Just what I was looking for. Thanks!

Mike us

5/6/2008 7:11:26 AM

Brett

Thank you for providing the one piece of information about error cs0120 that everyone else forgot to mention!

Brett us

7/1/2008 10:44:27 PM

Tarjei

You just made my day. Thanks.

Tarjei no

8/8/2008 8:24:47 AM

Bryce

1,000,000 hero points. Thanks for posting this info!

Bryce us

Add comment


(Will show your Gravatar icon)  

  Country flag





Live preview

9/5/2008 5:12:35 PM

Powered by BlogEngine.NET 1.2.0.0
Theme by Mads Kristensen

About the author

Name of author

My name is Bacon…James Bacon.

I am an API wars veteran I was wounded by x86 assembly, recovered and moved on to C. I am currently stuck in C++ and sniffing .NET.

I am mainly here to ramble about coding, various API’s, Junkies(me especially) and everything else that happens between coders and their significant other.

E-mail me Send mail


Calendar

<<  September 2008  >>
MoTuWeThFrSaSu
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345

View posts in large calendar

Pages

    Recent comments

    Authors

    Disclaimer

    The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

    © Copyright 2008

    Sign in