c# - SimpleMembership 更改用户名

标签 c# asp.net-mvc-4 simplemembership

我在 MVC4 应用程序中使用 SimpleMembership,需要用户能够更改自己的用户名。

我有这个功能,所以当用户更改他们的用户名时它可以工作。但是,当调用诸如 Roles.IsUserInrole() 之类的东西时,它会失败,因为 User.Identity.Name 设置为他们登录的内容,而不是新值。该值不再存在于数据库中,因为他们已更改名称。

我看不到用用户名更新登录用户上下文的方法。大多数情况下,我可以将用户 ID 存储在 session 中并在查询时检索它,但我使用 Roles 方法在失败的 View 中显示数据。

有什么想法吗?

谢谢!

最佳答案

这是我当前(有效)的解决方案:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(AccountEditModel model)
    {
        if (ModelState.IsValid)
        {
            if (HasSensitiveInformationChanged(model)) // model.EmailAddress.ToLower() != User.Identity.Name.ToLower()
            {
                if (Membership.ValidateUser(User.Identity.Name, model.Password)) // && WebSecurity.IsCurrentUser(User.Identity.Name)) //redundant?
                {
                    using (UsersContext db = new UsersContext())
                    {
                        UserProfile user = db.UserProfiles.FirstOrDefault(u => u.EmailAddress.ToLower() == User.Identity.Name.ToLower());

                        if (user != null)
                        {
                            user.EmailAddress = model.EmailAddress;
                            db.SaveChanges();
                            WebSecurity.Logout();
                            WebSecurity.Login(model.EmailAddress, model.Password);
                            return RedirectToAction("Index", "Search");
                        }
                        else
                        {
                            ModelState.AddModelError("", "Could not find user. Please try logging in again.");
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError("","Could not change email address. Please verify your password and try again.");
                }
            }
            else
            {
                //no change
                return RedirectToAction("Index", "Search");
            }
        }

        return View("Index", model);
    }

关于c# - SimpleMembership 更改用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15171226/

相关文章:

asp.net-mvc - 具有多个数据库或提供程序的 MVC4 简单成员身份验证

c# - Asp.Net Core OData 4.0 中 BaseUrl 中的动态路由

asp.net-mvc-4 - TFS checkin 请求被中止: The request was canceled

c# - 对特定 Google Apps 域的 MVC4/Google OpenID 限制

带有DropDownList数据的ASP.NET MVC 4 ViewModel

asp.net-mvc - ReactJs - 访问 onclick 事件中的状态

asp.net-mvc-4 - 当“新密码无效”时,WebSecurity.ChangePassword何时会失败?

c# - 在 C# 中计算文本文件总行数的最快方法是什么?

c# - 隐藏下拉列表中的项目 - C#

c# - 从 Azure 函数将批量消息发送到服务总线主题