从HttpContext.Current.User获取AspNetUser

Per*_*rcy 6 c# asp.net-mvc asp.net-mvc-5

使用MVC 5。

我是新来的UsersIdentitiesClaims

我如何AspNetUser从那里得到HttpContext.Current.User?我知道,我可以使用HttpContext.Current.User.Identity.Name(这是用户的电子邮件地址,我的系统上),然后打AspNetUser表的用户,但有没有更好的办法让AspNetUserHttpContext.Current.User我失踪?例如它HttpContext.Current.User已经包含在某个地方了吗?

我曾经尝试过使用Google,但并未真正找到该特定问题的任何答案。

fir*_*ape 3

AspNetUser 不存储在 HttpContext.Current.User 属性中。IPrincipal 对象由 HttpContext.Current.User 返回,IPrincipal 上指定的唯一成员是 IIdentity Identity 和 bool IsInRole。然后,IIdentity 接口为您提供 Name 属性,您可以使用该属性来查找实际的用户对象。

如果您只需要一行代码并具有对 User 对象的完全访问权限,则可以使用以下代码访问 AspNetUser:

ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());
Run Code Online (Sandbox Code Playgroud)

您将需要以下 using 语句:

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
Run Code Online (Sandbox Code Playgroud)

请注意,如果可以的话,最好通过 UserManager API,并且一旦获得 User 对象,您就可以通过 UserManager 更新方法进行编辑并保存更改。许多更改可以直接通过 UserManager 方法进行。如果您有 UserManager 的实例,您还可以通过以下方式访问 User 对象:

ApplicationUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
Run Code Online (Sandbox Code Playgroud)