我在这里遵循了一个 SO 答案来实现自定义声明:
How to extend available properties of User.Identity
但是,我的问题是它从不返回值。这是我的实现:
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;
}
}
}
现在我尝试在 View 中调用它进行测试:
<script>alert(@User.Identity.GetCustomUrl());</script>
该值始终为空,但是如果我更改为 @User.Identity.GetUserId()
,它会返回 Id。
我是不是漏掉了一步?
最佳答案
它是一个字符串,因此您应该使用:alert('@User.Identity.GetCustomUrl()');
注意引号,否则 'javascript' 会搜索名称为它的对象返回。如果它本身可以包含单引号,也不要忘记在此处转义该值。
关于c# - MVC5 中的自定义声明不返回任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35256117/