【问题标题】:Access custom properties on ApplicationUser class in EF Core 2.0.1在 EF Core 2.0.1 中访问 ApplicationUser 类的自定义属性
【发布时间】:2018-09-10 20:40:15
【问题描述】:

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

我的ApplicationUser.cs中有以下内容

public class ApplicationUser : IdentityUser
{
  public string DisplayUsername { get; set; }
}

在我的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 最新稳定版的正确做法是什么?

【问题讨论】:

    标签: c# asp.net-core entity-framework-core


    【解决方案1】:

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

     // Gets the System.Security.Claims.ClaimsPrincipal for user 
     // associated with the executing action.
     public ClaimsPrincipal User { get; }
    

    【讨论】:

    • 谢谢@Set,但你能详细说明一下吗?我将如何访问DisplayUsername 属性?
    • @Ciwan 实际上和你以前做的一样。检查User.Claims 并使用ClaimTypes.GivenName 类型从声明中获取值。替代您的代码方式可能是var name = User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.GivenName)?.Value;
    • 谢谢Set,我试过了,但我得到一个错误。显然,用户是null。见screenshot
    • @Ciwan 这是因为您尝试在控制器构造函数中获取用户,该构造函数在设置 ActionContext 之前被调用,因此您对 Context、Request 或 User 等属性具有空值。您应该改为在操作方法中执行此操作。检查这个SO post
    • 我明白了,所以我必须创建一个 ActionFilter 以使 ViewBag 中的 DisplayUsername 属性对所有控制器都可用
    猜你喜欢
    • 2018-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-04
    • 2019-12-11
    相关资源
    最近更新 更多