且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我应该如何从ASP.NET Core视图访问我的ApplicationUser属性?

更新时间:2023-02-16 16:35:12

更新为原始答案:(这违反了操作员的第一个要求,如果您有相同的要求,请参阅我的原始答案).可以通过在Razor视图中将FullName引用为

Update to original answer: (This violates the op's first requirement, see my original answer if you have the same requirement) You can do it without modifying the claims and adding the extension file (in my original solution) by referencing FullName in the Razor View as:

@UserManager.GetUserAsync(User).Result.FullName

原始答案:

这几乎只是此***问题的简短示例并遵循此假定您已经在"ApplicationUser.cs"中设置了属性以及适用于注册的ViewModels和Views.

Assuming you already have the property set up in the "ApplicationUser.cs" as well as the applicable ViewModels and Views for registration.

使用全名"作为额外属性的示例:

将"AccountController.cs"注册方法修改为:

Modify the "AccountController.cs" Register Method to:

    public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email,
                    Email = model.Email,
                    FullName = model.FullName //<-ADDED PROPERTY HERE!!!
                };
                var result = await _userManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    //ADD CLAIM HERE!!!!
                    await _userManager.AddClaimAsync(user, new Claim("FullName", user.FullName)); 

                    await _signInManager.SignInAsync(user, isPersistent: false);
                    _logger.LogInformation(3, "User created a new account with password.");
                    return RedirectToLocal(returnUrl);
                }
                AddErrors(result);
            }

            return View(model);
        }

然后我添加了一个新文件"Extensions/ClaimsPrincipalExtension.cs"

And then I added a new file "Extensions/ClaimsPrincipalExtension.cs"

using System.Linq;
using System.Security.Claims;
namespace MyProject.Extensions
    {
        public static class ClaimsPrincipalExtension
        {
            public static string GetFullName(this ClaimsPrincipal principal)
            {
                var fullName = principal.Claims.FirstOrDefault(c => c.Type == "FullName");
                return fullName?.Value;
            }   
        }
    }

,然后在您需要访问属性的视图中添加:

and then in you views where you need to access the property add:

@using MyProject.Extensions

并在需要时调用它:

@User.GetFullName()

一个问题是,即使数据库中具有FullName属性,我也必须删除当前的测试用户,然后重新注册才能看到"FullName".

The one problem with this is that I had to delete my current test user and then re-register in order see the "FullName" even though the database had the FullName property in it.