获取当前用户对象asp.net MVC 5

时间:2014-04-29 01:46:23

标签: asp.net asp.net-mvc asp.net-identity

我对asp.net MVC5中的用户身份验证感到困惑......我一直在引用这篇文章:

http://blogs.msdn.com/b/webdev/archive/2013/10/16/customizing-profile-information-in-asp-net-identity-in-vs-2013-templates.aspx

这个问题:

MVC 5 Custom UserStore ASP.net Identity - How does UserManager<TUser> Have Access To Roles?

......并且绝对知道在哪里。这是我的IdentityModel.cs中的代码

namespace attempt_4.Models
{

public class ApplicationUser : IdentityUser
{
     public string FirstName { get; set; }
}

public class MyUserStore : IUserStore<ApplicationUser>
{
}

public class ApplicationDbContext<ApplicationUser> : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection")
    {
    }
}
}

在控制器中我试图用以下内容获取UserObject:

   var userManager = new UserManager<ApplicationUser>(new MyUserStore<ApplicationUser>(new ApplicationDbContext()));
  var user = userManager.FindById(User.Identity.GetUserId());

这给我带来了大量的编译错误,最多的是attempt_4.Models.MyUserStore<ApplicationUser>' does not implement interface member 'System.IDisposable.Dispose(),但也有人说ApplicationUser不能用作Type参数'TUser'。

目前我正在使用:

var id = User.Identity.GetUserId();
var user = db.Users.First(x => x.Id == id);

这不是最好的方法,毫无疑问,由于[Authorize]已经查询了数据库。

我不需要任何涉及角色或任何花哨的东西...只是想扩展用户模型并能够从其他模型引用它来做这样的事情:db.Apartments.where(apt => apt.OwnerId == currentUserID)。也就是说,将表链接到User表的最佳做法是什么?我应该在ApplicationUser类中有一个int id来查询吗?或者我应该使用Guid吗?

1 个答案:

答案 0 :(得分:3)

您收到错误是因为您没有实现您所声明的接口(IUserStore)。也没有必要制作自己的UserStore,你可以使用开箱即用的那个:

new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()))

如果这不符合您的要求,这里有一个很好的指导如何自己实现ASP.NET身份:http://odetocode.com/blogs/scott/archive/2014/01/20/implementing-asp-net-identity.aspx

另外,我认为[Authorize]只是授权用户的cookie,而不是以任何方式查询数据库。