2014-12-29 34 views
0

我想添加一些自定义身份配置文件信息到我的asp mvc 5应用程序,并遇到麻烦。这是我第一次使用MVC或Identity(来自Web Forms),经过几个小时的研究,我仍然难倒了。无法访问自定义配置文件

我跟着http://blogs.msdn.com/b/webdev/archive/2013/10/16/customizing-profile-information-in-asp-net-identity-in-vs-2013-templates.aspx的指南,并添加了我应该的一切。

模型

Models/IdentityModel.cs 

public class ApplicationUser : IdentityUser 
{ 
    public string FirstName { get; set; } 
    public string MiddleName { get; set; } 
    public string LastName { get; set; } 
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) 
    { 
     // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType 
     var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); 
     // Add custom user claims here 
     return userIdentity; 
    } 
} 

AccountViewModel

Models/AccountViewModel 
... 
    [Required] 
    [Display(Name = "First Name")] 
    public string FirstName { get; set; } 
    [Required] 
    [Display(Name = "Middle Name")] 
    public string MiddleName { get; set; } 
    [Required] 
    [Display(Name = "Last Name")] 
    public string LastName { get; set; } 

我还修改了账户控制器和视图注册索要并保存新的信息。注册时,没有问题,我的应用程序正确保存了dbo.AspNetUsers(我可以在SQL Server Management Studio中查看数据)的名字,中间名和姓氏。

但是,我完全无法检索任何这些信息。我试图遵循执行控制器中的下列指南:“currentUser”

var currentUserId = User.Identity.GetUserId(); 
var manager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(new ApplicationDbContext())); 
var currentUser = manager.FindById(User.Identity.GetUserId()); 

但是当我型,我看到的是“AccessFailedCount,权利要求书,电子邮件,EmailConfirmed”等IntelliSense不显示与第一,中间或最后一个名字相关的任何内容。我试图连接到dbo.AspNetUsers并自己动手,但似乎并不想让我这样做。

我在做什么错?我的修改后的配置文件保存正确,但我不知道如何访问它保存的内容。

回答

0

您需要访问UserManager通过OwinContext

public ApplicationUserManager UserManager 
{ 
    get 
    { 
     return HttpContext.GetOwinContext() 
      .GetUserManager<ApplicationUserManager>(); 
    } 
} 

然后就可以调用UserManager.FindById和访问自定义属性。

ApplicationUser user = UserManager.FindById(User.Identity.GetUserId()); 
string middleName = user.MiddleName; 
+0

太棒了!我之前从未听说过OwinContext,但这段代码完全符合我的需要。非常感谢您的帮助! – Zach