我在我的项目中有一个文章实体,它具有名为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


当前回答

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

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

其他回答

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

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

以下是我的工作:

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

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

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

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

var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var user = manager.FindById(User.Identity.GetUserId());
ApplicationDbContext context = new ApplicationDbContext();
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
ApplicationUser currentUser = UserManager.FindById(User.Identity.GetUserId());

string ID = currentUser.Id;
string Email = currentUser.Email;
string Username = currentUser.UserName;

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

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

using Microsoft.AspNet.Identity;