简体   繁体   中英

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:

<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

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

 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.

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

In Razor Page

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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