访问自定义配置文件时遇到问题

本文关键字:遇到 问题 配置文件 自定义 访问 | 更新日期: 2023-09-27 18:35:46

我正在尝试向我的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;
    }
}

帐户视图模型

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中看到数据)。

但是,我完全无法检索任何这些信息。我试图通过在控制器中执行以下操作来遵循指南:

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

但是当我输入"currentUser."时,我看到的只是"AccessFailedCount,Claims,Email,EmailConfirmed"等。 Intellisense不显示与名字,中间名或姓氏相关的任何内容。我试图只连接到dbo。AspNetUser和自己拉东西,但它似乎不想让我这样做。

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

访问自定义配置文件时遇到问题

您需要

通过OwinContext访问UserManager

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

然后,您可以调用UserManager.FindById并访问自定义属性。

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