更改用户名后是否可以更改HttpContext.Current.User.Identity.Name

时间:2015-10-22 11:26:21

标签: asp.net-mvc mongodb asp.net-identity username

我正在开发一个ASP MVC应用程序。并希望在不进行用户注销的情况下更改用户名。我正在使用Identity Provider版本1.0.11。我的代码如下:

var updtUser = UserManager.FindById(model.UserId);

        updtUser.UserName = model.PrivateEMail;
        var res = await UserManager.UpdateAsync(updtUser);

        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
               updtUser.UserName,
               DateTime.Now,
               DateTime.Now,
               false,
               "someData",
               FormsAuthentication.FormsCookiePath);

        string encTicket = FormsAuthentication.Encrypt(ticket);

        Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));           

        return RedirectToAction("RedirectToDashbord", "Dashboard", new { area = "CRM"});

但是在这个操作之后HttpContext.Current.User.Identity.Name没有改变。任何帮助都会很棒

1 个答案:

答案 0 :(得分:1)

您应该立即撤销Cookie(+):

app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account.  
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromSeconds(0),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });