繁体   English   中英

如何将属性添加到@ User.Identity或声明在剃刀页面中使用

[英]how to add property to @User.Identity or on claim to use in razor page

我不能在ASP.NET Core中扩展我的Identity属性以在剃刀页面中使用,如下所示:

<input type="text" class="hidden" name="Id" id="Id" value="@User.Identity.Id">

我尝试使用它,但它不起作用:

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<AppUser> manager)
{
    var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
    userIdentity.AddClaim(new Claim("Id", this.PublicId));
    return userIdentity;
}

尝试使用IClaimsTransformation

public class CustomClaimsTransformer:IClaimsTransformation
{
    public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
    {
        ((ClaimsIdentity)principal.Identity).AddClaim(new Claim("Id", Claim.Value you want));
        return Task.FromResult(principal);
    }
}

向Startup.cs添加声明转换服务

 services.AddTransient<IClaimsTransformation, CustomClaimsTransformer>();

然后尝试HttpContext.User.Claims来检索用户的声明,但它将适用于子请求而不是当前的登录请求。

 ViewData["Id"] = HttpContext.User.Claims.First(c => c.Type == "Id").Value;

在Razor Page

<input type="text" class="hidden" name="Id" id="Id" value="@ViewData["Id"]">

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM