c# - MVC5 中的自定义声明不返回任何内容

标签 c# asp.net-mvc-5 asp.net-identity

我在这里遵循了一个 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/

相关文章:

c# - 找不到 CSC 中的源文件

c# - 模拟鼠标事件

c# - 通过使用 asp net identity 2.1 发送重置帐户链接来重置用户锁定

c# - 在用户注册身份时为用户设置角色的正确方法

c# - Moq 不会调用 IAuthenticationManager SignIn 方法

c# - c# - 如何清除List<>中彼此相似的元素

c# - 创建数千个 Web 请求任务并使用 Task.WhenAll() 等待它们是否安全

c# - ActionLink 不正确处理 URL,但 RouteLink 正确处理属性路由

asp.net-identity - 角色不起作用 - 错误地显示为用户不在角色中,.NET 6(从 .Net Core 3.2 升级)

.net-core - 查找生成器 'identity' ...给定的程序集名称或代码库无效