Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use HttpContext.Current.Session in static property of a abstract class.?

Tags:

c#

asp.net-mvc

I have a ControllerBase abstract class and as below.

using System.Web;
using System.Web.Mvc;
public abstract class ControllerBase : Controller
{
    public static string SesssionId
    {
         get { return HttpContext.Current.Session["SessionId"]; }
    }
}

I am getting Error

"object reference is required for the non-static field, method, or property 'System.Web.Mvc.Controller.HttpContext.get"

However I have used the same in other static classes and have not got the above error.

I wonder how the HttpContext is being accessable but not the current.

Could anyone clarify me, what is wrong with the above.

like image 298
Sravan Avatar asked Feb 16 '23 12:02

Sravan


1 Answers

Your base class Controller specifies a HttpContext property itself. So, when using it in your derived class ControllerBase, the compiler thinks you want to refer to this property of the base class.

You could either make the property non-static, as wudzik suggested in the first comment. I guess this would be the cleaner way to do it.

If you need to keep this property static, you have to tell the compiler, that you want to use the HttpContext class of namespace System.Web:

public static string SesssionId
{
     get { return System.Web.HttpContext.Current.Session["SessionId"]; }
}
like image 138
Dennis Avatar answered May 12 '23 14:05

Dennis