加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ajax – 设置HttpContext.Current.User

发布时间:2020-12-16 03:07:19 所属栏目:百科 来源:网络整理
导读:我正在开发一个asp.net mvc 3.0应用程序,它具有简单的身份验证过程.用户填写一个表单,该表单通过ajax调用发送到服务器并获得响应,但这里的问题是使用以下方法: FormsAuthentication.SetAuthCookie(person.LoginName,false); 是不足以填充’HttpContext.Curr
我正在开发一个asp.net mvc 3.0应用程序,它具有简单的身份验证过程.用户填写一个表单,该表单通过ajax调用发送到服务器并获得响应,但这里的问题是使用以下方法:
FormsAuthentication.SetAuthCookie(person.LoginName,false);

是不足以填充’HttpContext.Current.User’,它需要运行以下方法:

FormsAuthentication.RedirectFromLoginPage("...");

问题在于,正如我所提到的,loggin表单使用ajax表单,并使用json获取响应,因此无法重定向.

我怎么能填写’HttpContext.Current.User’?

谢谢.

更新:

这是注册方法:

[HttpPost]
        public ActionResult Register(Person person)
        {
            var q = da.Persons.Where(x => x.LoginName == person.LoginName.ToLower()).FirstOrDefault();

            if (q != null)
            {
                ModelState.AddModelError("","Username is repettive,try other one");

                return Json(new object[] { false,this.RenderPartialViewToString("RegisterControl",person) });
            }
            else
            {
                if (person.LoginName.ToLower() == "admin")
                {
                    person.IsAdmin = true;
                    person.IsActive = true;
                }

                da.Persons.Add(person);

                da.SaveChanges();

                FormsAuthentication.SetAuthCookie(person.LoginName,false);
return Json(new object[] { true,"You have registered successfully!" });

}

}
这是我最终使用的版本,它基于@ AdamTuliper-MSFT的答案.它只能在登录后立即使用,但在重定向之前,允许其他代码访问HttpContext.User.

>如果已经过身份验证,请不要做任何事情
>不修改cookie,因为这应仅用于此请求的生命周期
>缩短一些东西,用userdata更安全一些(永远不应该为null,但……)

在调用SetAuthCookie()后调用此方法,如下所示:

// in login function
FormsAuthentication.SetAuthCookie(model.UserName,model.RememberMe);
AuthenticateThisRequest();

private void AuthenticateThisRequest()
{
    //NOTE:  if the user is already logged in (e.g. under a different user account)
    //       then this will NOT reset the identity information.  Be aware of this if
    //       you allow already-logged in users to "re-login" as different accounts 
    //       without first logging out.
    if (HttpContext.User.Identity.IsAuthenticated) return;

    var name = FormsAuthentication.FormsCookieName;
    var cookie = Response.Cookies[name]; 
    if (cookie != null)
    {   
        var ticket = FormsAuthentication.Decrypt(cookie.Value);
        if (ticket != null && !ticket.Expired)
        {
            string[] roles = (ticket.UserData as string ?? "").Split(',');
            HttpContext.User = new GenericPrincipal(new FormsIdentity(ticket),roles);
        }
    }
}

编辑:删除对Request.Cookies的调用,如@ AdamTuplier-MSFT所述.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读