【问题标题】:Trouble accessing custom profile无法访问自定义配置文件
【发布时间】:2014-12-30 08:06:57
【问题描述】:

我正在尝试向我的 asp mvc 5 应用程序添加一些自定义身份配置文件信息,但遇到了麻烦。这是我第一次使用 MVC 或 Identity(来自 Web 表单),经过数小时的研究,我仍然感到困惑。

我按照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.AspNetUsers 并自己拉东西,但它似乎不想让我这样做。

我做错了什么?我修改后的个人资料正在正确保存,但我不知道如何访问它保存的内容。

【问题讨论】:

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


    【解决方案1】:

    您需要通过OwinContext访问UserManager。

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

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

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

    【讨论】:

    • 太棒了!我以前从未听说过 OwinContext,但这段代码正是我所需要的。非常感谢您的帮助!
    猜你喜欢
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-09
    • 1970-01-01
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多