2014-12-29 36 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