我在我的项目中有一个文章实体,它具有名为Author的ApplicationUser属性。如何获取当前登录的ApplicationUser的完整对象?在创建新文章时,我必须将article中的Author属性设置为当前的ApplicationUser。

在旧的会员机制中,这很简单,但在新的身份方法中,我不知道如何做到这一点。

我试着这样做:

为身份扩展添加using语句: 然后我尝试获取当前用户:ApplicationUser currentUser = db.Users。FirstOrDefault(x => x.Id == User.Identity.GetUserId());

但我得到了以下异常:

LINQ to Entities不识别方法System。字符串GetUserId(System.Security.Principal.IIdentity)方法,该方法不能转换为存储表达式。 源= EntityFramework


当前回答

有一个简单的方法:

User.Identity.Name

它提供当前用户的Id。

其他回答

现在asp。MVC项目模板创建一个帐户控制器,以这种方式获取用户管理器:

HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>()

以下是我的工作:

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

它在答案的评论中,但没有人把它作为实际的解决方案。

你只需要在顶部添加一个using语句:

using Microsoft.AspNet.Identity;

Ellbar的代码起作用了!你只需要加上using。

1 -使用Microsoft.AspNet.Identity;

和…Ellbar的代码:

2 - 字符串 currentUserId = User.Identity.GetUserId(); 应用程序用户当前用户 = db。Users.FirstOrDefault(x => x.Id == currentUserId);

使用这段代码(在currentUser中),您可以处理连接用户的一般数据,如果您需要额外的数据…请看这个链接

如果有人在web表单中使用身份用户,我通过这样做得到了它的工作:

var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var user = manager.FindById(User.Identity.GetUserId());

截至ASP。NET Identity 3.0.0,这已经被重构成

//returns the userid claim value if present, otherwise returns null
User.GetUserId();