简体   繁体   English

为什么会话对象抛出空引用异常?

[英]Why does session object throw a null reference exception?

on some of my aspx page I am checking session like this 在我的一些aspx页面上,我正在检查这样的会话

if (bool.Parse(Session["YourAssessment"].ToString()) == false
    && bool.Parse(Session["MyAssessment"].ToString()) == true)
{
    Response.Redirect("~/myAssessment.aspx");
}

It works fine if I keep playing with the pages frequently, but if I don't do anything with the page at least even for 5 min, running the page throws the error 如果我经常继续播放页面,它工作正常,但如果我至少在5分钟内没有对页面做任何事情,那么运行页面会引发错误

Object reference not set to an instance of an object.

Following is the stack for this 以下是此堆栈

[NullReferenceException: Object reference not set to an instance of an object.]
   yourAssessment.Page_Load(Object sender, EventArgs e) in d:\Projects\NexLev\yourAssessment.aspx.cs:27
   System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
   System.Web.UI.Control.OnLoad(EventArgs e) +91
   System.Web.UI.Control.LoadRecursive() +74
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2207

Could some body explain me this weird behaviour? 有些人可以解释一下这种奇怪的行为吗?

And as we know by default the session last for is 20 min. 正如我们所知,默认情况下会话持续时间为20分钟。

EDITED EDITED

See I have a page default aspx, it has got a button which fixes on the some basis where to redirect On default page it check like this 看到我有一个页面默认的aspx,它有一个按钮,修复了一些基础上的重定向在默认页面它检查像这样

protected void Page_Load(object sender, EventArgs e)
{
    if (!HttpContext.Current.Request.IsAuthenticated)
    {
        Response.Redirect("~/login.aspx");
    }
    else
    {
        Session["YourAssessment"] = false;
        Session["MyAssessment"] = false;
    }
}

on button click it has 按钮点击它有

protected void imgClientFreeEval_Click(object sender,
    System.Web.UI.ImageClickEventArgs e)
{
    if (HttpContext.Current.Request.IsAuthenticated)
    {
        string sqlQuery = "SELECT count(*) FROM SurveyClient WHERE UserID='"
            + cWebUtil.GetCurrentUserID().ToString() + "'";
        SqlParameter[] arrParams = new SqlParameter[0];
        int countSurvey = int.Parse(
            Data.GetSQLScalerVarQueryResults(sqlQuery).ToString());
        if (countSurvey > 0)
        {
            Session["YourAssessment"] = true;
            Session["MyAssessment"] = false;
        }
        Response.Redirect((countSurvey > 0)
            ? "~/yourAssessment.aspx"
            : "~/myAssessment.aspx");
    }
    else
    {
        Response.Redirect("~/login.aspx");
    }

and on myAssessment page it check like this 在myAssessment页面上,它会像这样检查

protected void Page_Load(object sender, EventArgs e)
{
    if (!HttpContext.Current.Request.IsAuthenticated)
    {
        Response.Redirect("~/login.aspx");
    }
    else
    {
        if (Session["YourAssessment"] != null
            && Session["MyAssessment"] != null
            && bool.Parse(Session["YourAssessment"].ToString())
            && !bool.Parse(Session["myAssessment"].ToString()))
        {
            Response.Redirect("~/yourAssessment.aspx");
        }
    }
}

and on yourAssessmtn it check like this 并在你的assessmtn上检查这样

protected void Page_Load(object sender, EventArgs e)
{
    if (!HttpContext.Current.Request.IsAuthenticated)
    {
        Response.Redirect("~/login.aspx");
    }
    else
    {
        if (Session["YourAssessment"] != null
            && Session["MyAssessment"] != null
            && !bool.Parse(Session["YourAssessment"].ToString())
            && bool.Parse(Session["MyAssessment"].ToString()))
        {
            Response.Redirect("~/myAssessment.aspx");
        }

        PopulateAllSurveyByUser();
        if (ViewState["surveyClientID"] != null)
        {
            grdSurveyDetail.Visible = true;
            PopulateSurveyDetails(
                int.Parse(ViewState["surveyClientID"].ToString()));
        }
        else
        {
            grdSurveyDetail.Visible = false;
        }
    }
}

what's wrong please explain? 有什么问题请解释一下?

You first need to check whether that session variable exists 首先需要检查该会话变量是否存在

if(Session["YourAssessment"] != null)
    // Do something with it
else
    // trying to call Session["YourAssessment"].ToString() here will FAIL.

That happens since your session has a lifecycle, which means - it expires (the cookie that defines it expires) - thus your objects vanish. 发生这种情况,因为你的会话有一个生命周期,这意味着 - 它到期(定义它的cookie到期) - 因此你的对象消失了。 you could increase sessionState timeout in web.config for your sessions to last longer. 您可以在web.config中增加sessionState timeout ,以使会话持续更长时间。

For example, in web.config 例如,在web.config中

  <system.web>
      <sessionState timeout="40" />
  </system.web>

Will make your sessions last for 40 minutes, as long as the client doesn't clear it, and the web server is up&running. 只要客户端不清除它,并且Web服务器启动并运行,您的会话将持续40分钟。

Always check for null when accessing Session object! 访问Session对象时始终检查null!
You can write some small utility that can be used for that: 您可以编写一些可用于此的小实用程序:

public class SessionData
{
    public static T Get<T>(string key)
    {
        object value = HttpContext.Current.Session[key];

        if(value == null)
            return default(T);

        try
        {
            return (T)value;
        }
        catch(Exception e)
        {
            return default(T);
        }
    }

    public static void Put(string key, object value)
    {
        HttpContext.Current.Session[key] = value;
    }
}

Session can be null if app pool is recycled. 如果应用程序池被回收,则会话可以为null。 That can happen because numerous reasons... 这可能是因为众多原因......

One trick for keeping your server from loosing session is making "pings" to server from javascript. 保持服务器不会丢失会话的一个技巧是从javascript向服务器“ping”。 It can make requests to some dummy url (empty page, or if you're perf freak, to .ashx handler) every minute or so. 它可以每隔一分钟向一些虚拟URL(空页,或者如果你是一个狂热的,对.ashx处理程序)发出请求。 It can be useful for pages that you keep open for long time, like huge edit forms. 它对于长时间打开的页面非常有用,例如巨大的编辑表单。
Also, beware, there are different session timeout values for debug and release configuration! 另外,请注意,调试和发布配置有不同的会话超时值!

First you can use you code like this 首先,您可以使用这样的代码

if (!bool.Parse(Session["YourAssessment"].ToString()) && 
     bool.Parse(Session["MyAssessment"].ToString()))
    Response.Redirect("~/myAssessment.aspx");

You sure you Sessions are not null 您确定Sessions不为null

Check like this 像这样检查

if (Session["YourAssessment"] != null && Session["MyAssessment"] != null && 
    !bool.Parse(Session["YourAssessment"].ToString()) && 
     bool.Parse(Session["MyAssessment"].ToString()))
        Response.Redirect("~/myAssessment.aspx");

如果Session不为null,请重新检查它是否具有"YourAssessment""MyAssessment"

When your Session expires the objects you have placed in your session such as Session["YourAssessment"] become null and the .toString() method call on those objects will then throw an Object reference error. 当Session到期时,您在会话中放置的对象(例如Session [“YourAssessment”])将变为null,并且对这些对象的.toString()方法调用将引发Object引用错误。 To work around this you must first check to make sure your session variables being null before attempting to perform the toString(). 要解决此问题,必须先检查以确保在尝试执行toString()之前会话变量为null。

    if(Session["YourAssessment"] != null){
if (bool.Parse(Session["YourAssessment"].ToString()) == false &&    bool.Parse(Session["MyAssessment"].ToString()) == true)
        {
            Response.Redirect("~/myAssessment.aspx");
        }
    }

Instead of the .ToString and Boolean.Parse do Convert.ToBoolean(Session["YourAssessment"]) 而不是.ToString和Boolean.Parse做Convert.ToBoolean(Session["YourAssessment"])

When I try Boolean b = Convert.ToBoolean(null) b = false ;) 当我尝试Boolean b = Convert.ToBoolean(null) b = false;)

Well after all that have been written about this it seems that problem is IIS application restarting and if your session is stored inproc that can couse deletion of session variables. 好了之后关于这一点的问题似乎问题是IIS应用程序重新启动,如果你的会话存储在可以删除会话变量的会话中。 So try to log application end events and see if this is a case, put this in Global.asax.cs application_end event, this code would log application restart and why it happened : 因此,尝试记录应用程序结束事件并查看是否是这种情况,将其放在Global.asax.cs application_end事件中,此代码将记录应用程序重新启动以及发生的原因:

protected void Application_End(object sender, EventArgs e)
{
  HttpRuntime runtime = (HttpRuntime)typeof(System.Web.HttpRuntime).InvokeMember("_theRuntime", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.GetField, null, null, null);

  string shutDownMessage = "";

  if (runtime != null)
  {
    shutDownMessage = Environment.NewLine + "Shutdown: " +
                      (string)runtime.GetType().InvokeMember("_shutDownMessage", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField, null, runtime, null) + 
                      Environment.NewLine + "Stack: " + Environment.NewLine +
                      (string)runtime.GetType().InvokeMember("_shutDownStack", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField, null, runtime, null);
  }

  string logFile =  HttpContext.Current.Server.MapPath(~/AppEndLog.log");
  string logMsg = "";
  if (File.Exists(logFile))
    logMsg = logMsg + File.ReadAllText(logFile) + Environment.NewLine + Environment.NewLine;
  logMsg = logMsg + Environment.NewLine + "ApplicationEnd - " + DateTime.Now.ToString() + shutDownMessage;
  File.WriteAllText(logFile, logMsg);


}

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

相关问题 为什么这个嵌套对象初始化器抛出一个空引用异常? - Why does this nested object initializer throw a null reference exception? 为什么这会引发空引用异常? - Why does this throw a null reference exception? 为什么Silverlight View不会引发null异常? - Why does Silverlight View not throw a null exception? 为什么 HttpRequestMessage.Content.Headers.ContentType 会抛出 null 引用异常? - Why does HttpRequestMessage.Content.Headers.ContentType throw null reference exception? 什么时候遍历列表会引发Null Reference Exception? - When does looping through a list throw a Null Reference Exception? 为什么会抛出异常 - Why does this throw exception 如果Any()为true,为什么LINQ在Count()上抛出空引用错误? - Why does LINQ throw a null reference error on Count() if Any() is true? 为什么MVC在似乎没有Null引用时会抛出NullReferenceException? - Why does MVC throw a NullReferenceException when there seems to be no Null Reference? 为什么对 DataRow 空值的这种取消引用不会引发异常? - Why does this dereference of a DataRow null value not throw an exception? .Net 2+:为什么 if( 1 == null ) 不再引发编译器异常? - .Net 2+: why does if( 1 == null ) no longer throw a compiler exception?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM