C# ASP.NET标识不是“非”;“储蓄”;更新的索赔
长话短说,我使用Identity,并在我的解决方案中创建了一个自定义帐户设置页面,该页面运行良好且漂亮。问题是我在C# ASP.NET标识不是“非”;“储蓄”;更新的索赔,c#,asp.net-mvc,asp.net-identity,identity,C#,Asp.net Mvc,Asp.net Identity,Identity,长话短说,我使用Identity,并在我的解决方案中创建了一个自定义帐户设置页面,该页面运行良好且漂亮。问题是我在\u Layout.cshtml中有用户FirstName和LastName。该名称由我拥有的自定义帮助器方法设置: public static MvcHtmlString GetUsersFirstAndLastName(this HtmlHelper helper) { string fullName = HttpContext.Current?.User?.Identit
\u Layout.cshtml
中有用户FirstName
和LastName
。该名称由我拥有的自定义帮助器方法设置:
public static MvcHtmlString GetUsersFirstAndLastName(this HtmlHelper helper)
{
string fullName = HttpContext.Current?.User?.Identity?.Name ?? string.Empty;
var userIdentity = (ClaimsPrincipal)Thread.CurrentPrincipal;
var nameClaim = identity?.FindFirst("fullname");
if (nameClaim != null)
{
fullName = nameClaim.Value;
}
return MvcHtmlString.Create(fullName);
}
这种方法非常有效,直到用户转到他们的个人资料并更新他们的姓名。如果他们将自己的名字从George
改为Bob
,那么当他们在我的网站上四处走动时,这种方法仍然将他们的名字改为George
,直到他们注销并重新登录
因此,我所做的是,当他们在帐户设置中更新自己的姓名时,我添加了一些代码来删除他们的旧fullName
声明,并添加新声明,如下所示:
var identity = User.Identity as ClaimsIdentity;
// check for existing claim and remove it
var currentClaim = identity.FindFirst("fullName");
if (currentClaim != null)
identity.RemoveClaim(existingClaim);
// add new claim
var fullName = user.FirstName + " " + user.LastName;
identity.AddClaim(new Claim("fullName", fullName));
使用这段代码,\u布局
视图现在更新名称(在我们前面的示例中,George
现在将更改为Bob
)。但是,当用户从该视图中单击到网站上的另一个位置或刷新页面时,它会立即变回George
对于identity仍然有点陌生,我有点困惑,为什么这个新的更新声明在他们点击不同的页面或刷新后不起作用。感谢您的帮助。:) 添加新索赔时,您还需要执行以下操作:
var authenticationManager = HttpContext.GetOwinContext().Authentication;
authenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant(new ClaimsPrincipal(identity), new AuthenticationProperties() { IsPersistent = true });
因此,新的完整代码块是:
public static MvcHtmlString GetUsersFirstAndLastName(this HtmlHelper helper)
{
string fullName = HttpContext.Current?.User?.Identity?.Name ?? string.Empty;
var userIdentity = (ClaimsPrincipal)Thread.CurrentPrincipal;
var nameClaim = identity?.FindFirst("fullname");
var authenticationManager = HttpContext.GetOwinContext().Authentication;
authenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant(new ClaimsPrincipal(identity), new AuthenticationProperties() { IsPersistent = true });
if (nameClaim != null)
{
fullName = nameClaim.Value;
}
return MvcHtmlString.Create(fullName);
}
你只需重新发布cookie即可