FormsAuthentication.SignOut抛出NullReferenceException

Sea*_*son 10 c# formsauthentication

这个问题似乎与这篇文章有关,但我无法从该帖子推断出一个解决方案.

我在我继承的应用程序中注意到这个代码(在日志文件中注意到正在吃异常):

    protected void Session_End(object sender, EventArgs e)
    {
        try
        {
            FormsAuthentication.SignOut();
            FormsAuthentication.RedirectToLoginPage();
            //if (this.Context.Handler is IRequiresSessionState || this.Context.Handler is IReadOnlySessionState)
            //{
            //    FormsAuthentication.SignOut();
            //    FormsAuthentication.RedirectToLoginPage();
            //}
        }
        catch (Exception ex)
        {
            this.GetType().GetLogger().Error(ex);
        }
    }
Run Code Online (Sandbox Code Playgroud)

我想知道一些事情.首先,SignOut如何抛出空引用异常?这是一个例外情况,还是我在我的计划中做了一些天生错误的事情?接下来,在抛出此异常之前,我应该测试什么来阻止它?

15:51:57,288 [13]错误ASP.global_asax - System.NullReferenceException:未将对象引用设置为对象的实例.在MvcApplication.Session_End的System.Web.Security.FormsAuthentication.SignOut()处

谢谢

Meh*_*ari 14

重要的是要意识到,Session_End不一定要在HTTP请求的上下文中执行.它可能会在会话超时时运行.你当时不能向客户发送任何东西,因为它根本就不存在了!

因此,您不应该尝试删除表单身份验证cookie Session_End.如果您愿意,在应用程序中的某处单击"注销"按钮时,应该尽快完成.如果您需要用户的表单身份验证票证在超时发生后到期,您只需在配置文件中适当地设置cookie到期时间(可能等于会话超时值).