长话短说,我使用身份,在我的解决方案中,我创建了一个自定义帐户设置页面,工作正常,花花公子。问题是我在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
。
对身份仍然有点新意我有点疑惑为什么这个新的更新声明在他们点击不同页面或刷新后不起作用。任何帮助表示赞赏。 :)
答案 0 :(得分:1)
添加新版权声明时,您还需要执行此操作:
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);
}