长话短说,我使用身份,在我的解决方案中,我创建了一个自定义帐户设置页面,该页面运行良好且美观。问题是我有用户FirstName
并且LastName
在_Layout.cshtml
。名称是由我具有的自定义帮助程序方法设置的:
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));
通过这段代码,_Layout
视图现在更新了名称(在我们之前的示例中,George
现在更改为Bob
)。但是,从该视图中单击该按钮到网站上的其他地方或刷新页面的那一刻,该更改会立即变为George
。
仍然对身份有点陌生,我有些困惑,为什么这个新的更新的声明在他们单击到另一个页面或刷新后不起作用。任何帮助表示赞赏。:)
添加新声明时,您还需要执行以下操作:
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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句