asp.net 身份声明在 View 页面中的全名

标签 asp.net asp.net-mvc-4 razor asp.net-mvc-5 asp.net-identity-2

我是 asp.net Identity 2.0 的新手,我想在用户名的 Razor View 页面中显示我的全名。

所以我向 IdentityUser 添加了新属性。

public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FullName => $"{FirstName} {LastName}";
}

默认 AccountController 包含登录方法:
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {           
        var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);

        switch (result)
        {
            case SignInStatus.Success:
                return RedirectToLocal(returnUrl);
            case SignInStatus.LockedOut:
                return View("Lockout");
            case SignInStatus.RequiresVerification:
                return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return View(model);
        }
    }

我编辑了这个登录方法
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {           
        var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);

        //-------------------------------------------------------
        if (result == SignInStatus.Success)
        {
            var user = await UserManager.FindByEmailAsync(model.Email);
            if (user != null)
            {
                await UserManager.AddClaimAsync(user.Id, new Claim("FullName", user.FullName));
            }
        }
        //--------------------------------------------------------

        switch (result)
        {
            case SignInStatus.Success:
                return RedirectToLocal(returnUrl);
            case SignInStatus.LockedOut:
                return View("Lockout");
            case SignInStatus.RequiresVerification:
                return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return View(model);
        }
    }

我创建了一个扩展方法来从 Razor View 中读取 FullName:
public static class IdentityExtensions
{
    public static string GetFullName(this IIdentity identity)
    {
        var claim = ((ClaimsIdentity) identity);

        return claim.FindFirst("FullName");            
    }
}

但 FullName 总是为 Null
<ul class="nav navbar-nav navbar-right">
    <li>
        @Html.ActionLink("Hello " + User.Identity.GetFullName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
    </li>
    <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
</ul>

最佳答案

您尝试添加声明的方式是在 UserClaims 中创建数据库条目。 table 。如果你想这样做,那么你必须在 await UserManager.AddClaimAsync(user.Id, new Claim("FullName", user.FullName)); 之前添加声明( PasswordSignInAsync )并且在我看来不在登录操作中。最好在添加和更新用户的名字和姓氏的操作中进行。

另一种方法是在 ClaimsIdentity 时添加此数据。登录时生成。在您的自定义中 IdentityUser类(class)有GenerateUserIdentityAsync方法,您可以简单地:

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        userIdentity.AddClaim(new Claim("LastName", $"{FirstName} {LastName}"));
        return userIdentity;
    }
}

关于asp.net 身份声明在 View 页面中的全名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35982571/

相关文章:

asp.net - Application Insight 中的 MVC 异常隐藏堆栈跟踪

c# - 如何获取 ItemDataBound 中 Repeater 中的项目计数

asp.net - DELETE 返回错误 405(方法不允许)我正在使用 React 和 ASP.Net Core

c# - Asp.NET MVC Razor 十进制格式?到 #。###,##

c# - MVC 4 区域路由不工作

c# - MVC无参数

c# - 命名空间 'Microsoft 中不存在类型或命名空间名称 'EntityFrameworkCore'

c# - SignalR 在 Hub 或 Controller 中实现 CRUD 方法

asp.net-mvc - 在调试 MVC View 时检查 HTML 输出

c# - asp.net MVC4 HtmlHelper 扩展和渲染函数