1

我试图在 asp.net MVC 4 应用程序中使用 FormsAuthentication。身份验证本身工作正常,但是每当我从 FormsAuthenticationEventArgs.User 获取用户并分配给 Http.Context.Current.User 时,它就在那个时刻工作,并且下一个调用方法如下 Http.Context.Current.User 再次为空......我究竟做错了什么?

protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e)
    {

        if (FormsAuthentication.CookiesSupported == true)
        {
            if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
            {
                try
                {
                    string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
                    var usuarioRn = new UsuarioRN();
                    string roles = usuarioRn.GetRoles(username);

                    FormsAuthenticationTicket ticket =  FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value);

                    e.User = new System.Security.Principal.GenericPrincipal(new   System.Web.Security.FormsIdentity(ticket), roles.Split(';'));
                    //First time get here assign e.User to HttpContext.Current.User, all good
                    //Next call HttpContext.Current.User is again null, why?
                    HttpContext.Current.User = e.User;                       
                }
                catch (Exception)
                {

                }
            }
        }
4

1 回答 1

0

FormsAuthenticationEventArgs.User只是为了让您可以将当前 HttpContext 的 User 属性设置为自定义 IPrincipal 对象。

如果它有这个签名可能会更容易理解:

FormsAuthenticationEventArgs.SetHttpContextUser(IPrinciple user);

换句话说,它总是为空——当你给它分配一些东西时,它实际上设置了其他东西(HttpContext User)。

于 2014-07-23T06:37:56.657 回答