HttpContext.Current.Session [" id"]!= null)

时间:2014-05-11 19:59:29

标签: asp.net-mvc-4

我有一个班级来检查用户是否登录了mvc 4网站。

但经过几次调用后,我收到以下错误:对象引用未设置为对象的实例。

导致错误的代码是: HttpContext.Current.Session [" id"]!= null)

using System.Web;


namespace mywebsite.BObjects
{
    public class SecurityManagement
    {
        public bool IsAuthenticatedWithActiveSession()
        {            
            if (HttpContext.Current.Request.IsAuthenticated && HttpContext.Current.Session["id"] != null)
            {
                return true;
            }
            else
            {
                return false;
            }

        }
    }
}

我使用剃刀视图来检查用户是否已登录

 @{
                        SecurityManagement verify = new SecurityManagement();

                        if (verify.IsAuthenticatedWithActiveSession())
                    {
                        <a href="@Url.Action("LogOut", "Account")">Log Out</a>
                    }
                    else
                    {
                        <a href="@Url.Action("Login", "Account")">Login</a>
                    }          
                    }   

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。我只需删除会话名称:

if (HttpContext.Current.Request.IsAuthenticated && HttpContext.Current.Session != null) { return true; } else { return false; }