问题描述:

I have followed a SO answer here to implement a custom Claim:

How to extend available properties of User.Identity

However, my problem is that it never returns a value. Here is my implementation:

using System.Security.Claims;

using System.Security.Principal;

namespace Events.Extensions

{

public static class IdentityExtensions

{

public static string GetCustomUrl(this IIdentity identity)

{

var claim = ((ClaimsIdentity)identity).FindFirst("CustomUrl");

// Test for null to avoid issues during local testing

return (claim != null) ? claim.Value : string.Empty;

}

}

}

namespace Events.Models

{

public class Member : IdentityUser

{

public string CustomUrl { get; set; }

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<Member> manager)

{

var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

userIdentity.AddClaim(new Claim("CustomUrl", this.CustomUrl));

return userIdentity;

}

}

}

And now I tried calling it in a view for testing:

<script>alert(@User.Identity.GetCustomUrl());</script>

The value is always nothing, however if I were to change to @User.Identity.GetUserId() then it would return me the Id.

Have I missed a step somewhere?

网友答案:

It is a string so you should use: alert('@User.Identity.GetCustomUrl()'); Note the quotes, because otherwise 'javascript' searches for an object with the name it returns. Also don't forget to escape the value here, if it could contain single quotes itself.

相关阅读:
Top