C# 更改HttpContext.Current.User.Identity.Name
在SetAuthCookie部分中,我们对用户名的操作有点像这样C# 更改HttpContext.Current.User.Identity.Name,c#,asp.net-mvc,httpcontext,roleprovider,C#,Asp.net Mvc,Httpcontext,Roleprovider,在SetAuthCookie部分中,我们对用户名的操作有点像这样 string userInfo = identity.Name + "|" + Util.GetIPAddress(); FormsAuthentication.SetAuthCookie(userInfo, isPersistent); 这是为了在应用程序_AuthenticateRequest中对用户IP地址进行一些检查 稍后,我想将名称恢复为正常名称,但没有|和IP地址,但找不到方法 我遇到的问题通常处理用户名没有正确更
string userInfo = identity.Name + "|" + Util.GetIPAddress();
FormsAuthentication.SetAuthCookie(userInfo, isPersistent);
这是为了在应用程序_AuthenticateRequest中对用户IP地址进行一些检查
稍后,我想将名称恢复为正常名称,但没有|和IP地址,但找不到方法
我遇到的问题通常处理用户名没有正确更新,但我需要的是重新分配用户名
我试图设置一个新的cookie并设置一个新的Authcookie,但它们不起作用,HttpContext.Current.User.Identity.Name没有更改
如何做到这一点?构建自己的身份验证cookie以添加所需的自定义值是一种更好的方法,这样可以使用户名保持不变,从而更加一致,达到预期的行为 考虑到这一点,您将在cookie中加密ip的用户数据
var cookie = FormsAuthentication.GetAuthCookie(name, rememberMe);
var ticket = FormsAuthentication.Decrypt(cookie.Value);
var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration,ticket.IsPersistent, userData, ticket.CookiePath);
var encTicket = FormsAuthentication.Encrypt(newTicket);
cookie.Value = encTicket;
//and add the cookie to the current HttpContext.Response
response.Cookies.Add(cookie);
此外,您还可以从当前User.Identity检索此userData
var data = (HttpContext.Current?.User.Identity as FormsIdentity)?.Ticket.UserData
对我来说,这似乎是一个XY问题-与其更改您的用户名,不如告诉我们您在需要用户IP地址的应用程序_AuthenticateRequest中尝试执行的操作。老实说,这也是我关心的问题之一。基本上,我们正在尝试将IP添加到cookie中,以便在相同用户从不同IP登录时检测IP更改并删除会话。我只是照我说的做。