我应该如何从ASP.NET Core视图访问我的ApplicationUser属性? [英] How should I access my ApplicationUser properties from ASP.NET Core Views?

查看:122
本文介绍了我应该如何从ASP.NET Core视图访问我的ApplicationUser属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究ASP.Net vNext/MVC6项目.我正逐渐熟悉ASP.Net身份.

I'm working on an ASP.Net vNext / MVC6 project. I'm getting to grips with ASP.Net Identity.

显然,应该在ApplicationUser类中添加任何其他用户属性,并且该类可与Entity Framework一起使用,并且我的其他属性将按预期方式存储在数据库中.

The ApplicationUser class is apparently where I'm supposed to add any additional user properties, and this works with Entity Framework and my additional properties get stored in the database as expected.

但是,当我想从视图中访问当前登录用户的详细信息时,就会出现问题.具体来说,我有一个_loginPartial.cshtml,我要在其中检索并显示用户的Gravatar图标,为此我需要电子邮件地址.

However, the problem comes when I want to access the details of the currently logged in user from within my views. Specifically, I have a _loginPartial.cshtml in which I want to retrieve and display the user's Gravatar icon, for which I need the email address.

Razor View基类具有一个User属性,它是一个ClaimsPrincipal.如何从此User属性返回到我的ApplicationUser,以检索我的自定义属性?

The Razor View base class has a User property, which is a ClaimsPrincipal. How do I go from this User property back to my ApplicationUser, to retrieve my custom properties?

请注意,我并不是在问如何查找信息.我知道如何从User.GetUserId()值中查找ApplicationUser.这更多是关于如何明智地解决此问题的问题.具体来说,我不想:

Note that I'm not asking how to find the information; I know how to lookup an ApplicationUser from the User.GetUserId() value. This is more a question about how to approach this problem sensibly. Specifically, I don't want to:

  • 从我的视图中进行任何类型的数据库查找(关注点分离)
  • 必须向每个控制器添加逻辑以检索当前用户的详细信息(DRY原理)
  • 必须向每个ViewModel添加一个User属性.

这似乎是一个跨领域关注点",应该有一个集中的标准解决方案,但是我感觉好像缺少了一块拼图游戏.从视图中获取那些自定义用户属性的最佳方法是什么?

This seems like a 'cross-cutting concern' that ought to have a centralized standard solution, but I feel like I'm missing a piece of the jigsaw puzzle. What is the best way to get at those custom user properties from within views?

注意:看来MVC团队通过确保始终将UserName属性设置为用户的电子邮件地址,从而在项目模板中避开了此问题,从而避免了他们进行此查找以获取用户的电子邮件地址的麻烦.电子邮件地址!这对我来说似乎有点作弊,在我的解决方案中,用户的登录名可能是也可能不是他们的电子邮件地址,因此我不能依靠该技巧(而且我怀疑以后还会需要其他属性) ).

Note: It seems that the MVC team has side-stepped this issue within the project templates by ensuring that the UserName property is always set to the user's email address, neatly avoiding the need for them to perform this lookup to get the user's email address! That seems like a bit of a cheat to me and in my solution the user's login name may or may not be their email address, so I can't rely on that trick (and I suspect there will be other properties I need to access later).

推荐答案

更新为原始答案:(这违反了操作员的第一个要求,如果您有相同的要求,请参阅我的原始答案).可以通过在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

原始答案:

这几乎只是此stackoverflow问题的简短示例并遵循此假定您已经在"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.

这篇关于我应该如何从ASP.NET Core视图访问我的ApplicationUser属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆