为什么HttpContext.Current.User无法初始化返回null

时间:2015-04-21 18:44:51

标签: asp.net-mvc

我使用此代码进行身份验证mvc。我正在登录,但当跟踪项目显示current.user null时,Context.User为空。 我认为Context.User无法初始化 怎么解决这个问题

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
    {
        if (Context.User == null)
            return;
        var userService = ObjectFactory.GetInstance<IUserService>();
        var userStatus =       userService.GetStatus(Context.User.Identity.Name);

        if (userStatus.IsBaned)
            FormsAuthentication.SignOut();

        var authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
        if (authCookie == null || authCookie.Value == "")
            return;

        var authTicket = FormsAuthentication.Decrypt(authCookie.Value);


        // retrieve roles from UserData
        if (authTicket == null) return;
        var roles = authTicket.UserData.Split(',');

        if (userStatus.Role != roles[0])
            FormsAuthentication.SignOut();

        Context.User = new GenericPrincipal(Context.User.Identity, roles);
    }
   private void SetAuthCookie(string userName, string roleofUser, bool presistantCookie)
    {
        var timeout = presistantCookie ? FormsAuthentication.Timeout.TotalMinutes : 30;

        var now = DateTime.UtcNow.ToLocalTime();
        var expirationTimeSapne = TimeSpan.FromMinutes(timeout);

        var authTicket = new FormsAuthenticationTicket(
            1,
            userName,
            now,
            now.Add(expirationTimeSapne),
            presistantCookie,
            roleofUser,
            FormsAuthentication.FormsCookiePath
            );

        var encryptedTicket = FormsAuthentication.Encrypt(authTicket);

        var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
        {
            HttpOnly = true,
            Secure = FormsAuthentication.RequireSSL,
            Path = FormsAuthentication.FormsCookiePath
        };

        if (FormsAuthentication.CookieDomain != null)
        {
            authCookie.Domain = FormsAuthentication.CookieDomain;
        }

        if (presistantCookie)
            authCookie.Expires = DateTime.Now.AddMinutes(timeout);

        Response.Cookies.Add(authCookie);
    }

0 个答案:

没有答案