简体   繁体   English

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

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

I can't extend my Identity property in ASP.NET Core to use in a razor page, like this: 我不能在ASP.NET Core中扩展我的Identity属性以在剃刀页面中使用,如下所示:

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

I try to use this, but it doesn't work: 我尝试使用它,但它不起作用:

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;
}

Try to use IClaimsTransformation 尝试使用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);
    }
}

Add a claims transformation service to Startup.cs 向Startup.cs添加声明转换服务

 services.AddTransient<IClaimsTransformation, CustomClaimsTransformer>();

Then try HttpContext.User.Claims to retrive the claims for the user, but it will work for sub-request instead of current login request. 然后尝试HttpContext.User.Claims来检索用户的声明,但它将适用于子请求而不是当前的登录请求。

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

In Razor Page 在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