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

asp.net-mvc-4 – 登录后WebSecurity.CurrentUserName和User.Ide

发布时间:2020-12-16 04:31:49 所属栏目:asp.Net 来源:网络整理
导读:我正在为我的ASP.Net MVC 4网站找出SimpleMembership.我用自定义属性AccountTypeId扩充了UserProfile.我已经使用augmented属性更新了数据库表,并且可以在注册时将数据保存到数据库中.关于如何在用户登录后检索有关用户的数据,我有点困惑. 在我的帐户控制器中
我正在为我的ASP.Net MVC 4网站找出SimpleMembership.我用自定义属性AccountTypeId扩充了UserProfile.我已经使用augmented属性更新了数据库表,并且可以在注册时将数据保存到数据库中.关于如何在用户登录后检索有关用户的数据,我有点困惑.

在我的帐户控制器中,我有一个登录操作,在用户登录时发布.这是我的代码:

[HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginModel model,string returnUrl)
    {
        if (ModelState.IsValid && WebSecurity.Login(model.UserName,model.Password,persistCookie: model.RememberMe))
        {
            var userName = WebSecurity.CurrentUserName;
            var identityName = User.Identity.Name;
            var currentuserid = WebSecurity.GetUserId(model.UserName);
            var context = new UsersContext();
            var user = context.UserProfiles.SingleOrDefault(u => u.UserId == currentuserid);
            var accountTypeId = user.AccountTypeId;

            return RedirectToLocal(returnUrl);
        }

        // If we got this far,something failed,redisplay form
        ModelState.AddModelError("","The user name or password provided is incorrect.");
        return View(model);
    }

WebSecurity.CurrentUserName和User.Identity.Name都是空字符串,但是,我可以使用WebSecurity.GetUserId(model.UserName)检索UserId,因此可以检索用户数据,我可以获得accountTypeId.

有些奇怪的是,User.Identity.Name在用户被重定向到登录页面后从.cshtml页面调用时会显示在我的页面上.因此,在我的控制器的Login操作和目标页面之间的某处,User.Identity正在设置数据.

我假设自从我通过WebSecurity.Login检查后,WebSecurity将获得有关登录用户的信息,但似乎不是这样.

我错过了什么?

解决方法

用户名将写入cookie.为了使cookie数据可用,必须将其放入Response并发送回浏览器.在下一个请求时,将读取cookie值并用于填充User.Identity.Name属性.

换句话说,在Redirect调用之前,User.Identity.Name属性应为空字符串.这是在登录后重定向的目的:将cookie写入浏览器,以便后续请求将用户视为已登录.

(编辑:李大同)

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

    推荐文章
      热点阅读