c# - 从 HttpContext.Current.User 获取 AspNetUser

标签 c# asp.net-mvc asp.net-mvc-5

<分区>

使用 MVC 5。

我是 UsersIdentitiesClaims 的新手。

如何从 HttpContext.Current.User 获取 AspNetUser?我知道我可以使用 HttpContext.Current.User.Identity.Name(这是我系统上用户的电子邮件地址)然后点击 AspNetUser 表用户,但是否有更好的方法从我缺少的 HttpContext.Current.User 获取 AspNetUser?例如它是否已包含在 HttpContext.Current.User 中?

我试过谷歌,但我并没有真正找到这个具体问题的任何答案。

最佳答案

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

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

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

您需要以下 using 语句:

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;

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

ApplicationUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

关于c# - 从 HttpContext.Current.User 获取 AspNetUser,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38039295/

相关文章:

c# - 用表达式定义的属性与传统方式有什么实际区别?

c# - 如果发生错误,则中止网络测试

javascript - Asp mvc razor 在文本框中存储输入文件的值

jquery - 在 MVC 中延迟内联脚本在 jquery 之后加载

visual-studio - Visual Studio 2015 Community Edition 有 MVC 模板吗?

c# - HTTP PATCH 方法 C#

c# - 对 EventWaitHandle 的名称感到困惑

javascript - 在 Angular/.NET MVC 中发出发布请求后如何使用模型进行重定向?

asp.net-mvc - 如何将 CSS、JS 和其他文件组织到 ASP MVC 4 中

asp.net-mvc-5 - Web api 2 Web 服务中的 Dispose 方法