C# 访问EF Core 2.0.1中ApplicationUser类的自定义属性

C# 访问EF Core 2.0.1中ApplicationUser类的自定义属性,c#,asp.net-core,entity-framework-core,C#,Asp.net Core,Entity Framework Core,我正在开发一个与EF Core 2.0.1(通过Pomelo的MySQL)相结合的.NET Core应用程序 我的ApplicationUser.cs中有以下内容 public class ApplicationUser : IdentityUser { public string DisplayUsername { get; set; } } 访问myBaseController.cs中的DisplayUsername属性的正确方法是什么?在.NET Framework中,我曾经在我的B

我正在开发一个与EF Core 2.0.1(通过Pomelo的MySQL)相结合的.NET Core应用程序

我的
ApplicationUser.cs中有以下内容

public class ApplicationUser : IdentityUser
{
  public string DisplayUsername { get; set; }
}
访问my
BaseController.cs
中的
DisplayUsername
属性的正确方法是什么?在.NET Framework中,我曾经在我的
BaseController.cs
中这样做:

public class BaseController : Controller
{
  public BaseController()
  {
    var prinicpal = (ClaimsPrincipal)Thread.CurrentPrincipal;
    var displayUsername = prinicpal.Claims.Where(c => c.Type == ClaimTypes.GivenName).Select(c => c.Value).SingleOrDefault();
    ViewBag.DisplayUsername = displayUsername;
  }
}

但这已经不起作用了,因为我们不能再做
Thread.CurrentPrinciple
。在最新稳定的.NET Core版本中,正确的方法是什么?

现在控制器类中有一个
User
属性(在
ControllerBase
类中定义):


谢谢@Set,但你能详细说明一下吗?我将如何访问
DisplayUsername
属性?@Ciwan实际上与您之前的方式相同。检查
User.Claims
并使用
ClaimTypes.GivenName
类型从索赔中获取值。代码方式的替代方法可能是
var name=User.Claims.FirstOrDefault(x=>x.Type==ClaimTypes.GivenName)?.Value谢谢设置,我尝试了,但我得到了一个错误。显然,用户是
null
。请参阅。@Ciwan这是因为您试图在设置
ActionContext
之前调用的控制器构造函数中获取用户,因此您的属性(如Context、Request或User)值为空。您应该改为在action方法中执行此操作。选中此复选框,我看到了,因此我必须创建一个ActionFilter,以便在ViewBag中为所有控制器提供
DisplayUsername
属性
 // Gets the System.Security.Claims.ClaimsPrincipal for user 
 // associated with the executing action.
 public ClaimsPrincipal User { get; }