MVC6 身份自定义字段检索

MVC6 Identity Custom Field Retrieval

我在 AspNetUsers table 中添加了一个名为 CompanyName 的新专栏。我希望在 API.

的查询中使用它

我已经使用 [Authorized] 属性得到

User.Identity.Name

这显然是获取了用户的名字。我正在寻找获得 CompanyName 的方法。

我是否必须直接查询 aspnetusers table 才能获取此信息?

下面的方法会帮你把custom data。 如果这没有帮助,请提供更多信息。比如你在哪里创建或检索它的源代码。

string username = HttpContext.Current.User.Identity.Name;
var identity = new MyIdentity(username, true);
var principal = new MyPrincipal(identity, identity.Roles);
HttpContext.Current.User = principal;

您需要创建用户的实例才能访问用户的属性,我使用 UserManager class 来创建用户。可能还有其他方法可以完成此操作,但这是我过去所做的。

控制器顶部class:

private Microsoft.AspNet.Identity.UserManager<YourApplication.Models.ApplicationUser> um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));//new up a UserManager

现在在动作方法中:

        public ActionResult Index()
        {
        ApplicationUser user = um.FindById(User.Identity.GetUserId());//Create an instance of the user
        ViewBag.CompanyName = user.CompanyName ;//Read the property
        return View();
        }