简体   繁体   English

在C#类中维护会话

[英]Maintaining session in a class C#

I am trying to maintain session in a class for MVC application . 我正在尝试为MVC应用程序的类维护会话。 Below is the code which i used get and set session in a variable. 以下是我在变量中使用get和set会话的代码。 But whenever i am accessing this variable after set, it is giving null. 但是,每当设置后我访问此变量时,它就会给出null。

public static class MySession
{
    public static string MyVar
    {
        get
        {
            return HttpContext.Current.Session["MyVar"] == null ? "" : HttpContext.Current.Session["MyVar"].ToString();
        }
        set
        {
            HttpContext.Current.Session["MyVar"] = value;
        }
    }
}

And I used to set as MySession.MyVar="testData"; 我曾经设置为MySession.MyVar="testData";

But when i access string str = MySession.MyVar; 但是当我访问string str = MySession.MyVar;

it gives null value. 它给出null值。 Does anybody know why my session is not stored? 有人知道为什么不保存我的会话吗?

Session variables are very much exposed to being null, that is each time a new session is created by user, browser, network or application itself. 会话变量非常容易为空,即每次由用户,浏览器,网络或应用程序本身创建新会话时。 That is why, it is very much recommended to wrap it around with if...else block. 这就是为什么,强烈建议使用if ... else块将其包装。

if(Session["key"] != null) {
   // Variable exists for the session
   // use variable
} else {
   // Variable doesn't exist in the session
   // create and user variable
}

However, if still you always get a null , then you should check what is going wrong. 但是,如果仍然总是得到null ,则应检查出了什么问题。 My bet is that there is some other code or process that terminates the previous sessions and restarts them. 我敢打赌,还有一些其他代码或过程可以终止先前的会话并重新启动它们。 You should know you can programmatically also remove all sessions, that might also cause this problem. 您应该知道您还可以以编程方式也删除所有会话,这也可能导致此问题。

Also, Session variables can be used and served using a class, there is no problem in that. 此外,可以使用类使用和提供Session变量,这没有问题。 Just make sure that the collection Session isn't being refreshed. 只需确保未刷新集合Session

My guess is you have not enabled session state. 我的猜测是您尚未启用会话状态。

<system.web>
    <sessionState mode="InProc" timeout="60"/>
<system.web>

Session state is disabled by default in MVC and is generally not recommended unless absolutely necessary. 在MVC中,默认情况下禁用会话状态,除非绝对必要,否则通常不建议使用该状态。

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

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