简体   繁体   English

如何在抽象类的静态属性中使用HttpContext.Current.Session。

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

I have a ControllerBase abstract class and as below. 我有一个ControllerBase抽象类,如下所示。

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" “对象引用是非静态字段,方法或属性'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. 我想知道HttpContext是如何可访问的而不是当前的。

Could anyone clarify me, what is wrong with the above. 谁能澄清我,上面有什么问题。

Your base class Controller specifies a HttpContext property itself. 您的基类Controller本身指定了HttpContext属性。 So, when using it in your derived class ControllerBase , the compiler thinks you want to refer to this property of the base class. 因此,在派生类ControllerBase使用它时,编译器认为您要引用基类的此属性。

You could either make the property non-static, as wudzik suggested in the first comment. 您可以使该属性非静态,如Wudzik在第一条评论中所建议的那样。 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 : 如果需要将此属性保持为静态,则必须告诉编译器,您要使用命名空间System.WebHttpContext类:

public static string SesssionId
{
     get { return System.Web.HttpContext.Current.Session["SessionId"]; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM