如何实现User.identity.getUserEmail()

时间:2015-10-24 19:45:11

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

用户应该拥有唯一的theme1而不是email。为实现此目的,我将电子邮件存储在UserName表的电子邮件列中的UserName和UserName中。现在我想在我的视图中访问用户名。方法AspNetUsers很棒,但现在我需要User.Identity.GetUserName()。我可以实施User.Identity.GetUserEmail()吗?

更新

我必须在每个视图中使用User.Identity.GetUserEmail()。当我使用User.Identity.GetUserEmail()时。 我想在User.Identity.GetUserId()命名空间中编写此方法,以便可以在任何地方访问它。

3 个答案:

答案 0 :(得分:0)

我必须在Identity模型中添加一个新值,并获取新值,我这样做了:

    private string GetUserEmail()
    {
        //Instantiate the UserManager in ASP.Identity system so you can look up the user in the system
        var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
        //Get the User object
        var currentUser = manager.FindById(User.Identity.GetUserId());
        return currentUser.Email;
    }

您可以在相关的控制器中构建它,或者它可以是其他地方的静态函数,您只需要引用标识。

个人注意事项:我必须说我不完全支持在用户名和电子邮件之间切换的想法。我认为您应该考虑编辑模型,这link可能有所帮助。

答案 1 :(得分:0)

首先我要说的是,我不喜欢在您的视图中执行代码的想法。此外,如果你每次都这样做,你就违反了DRY原则。

我认为你需要的是ASP.NET Identity framework。这允许您自定义身份验证和授权过程,包括检索用户信息的方式和位置。通过重写UserManager类,您可以开始覆盖所需的方法(如GetEmailAsync)。您还可以通过更改标识声明来修改CreateUserIdentity方法。

这样您只需定义一次规则,然后就可以在整个应用程序中使用。但为了实现这一目标,您必须自己对ASP.NET身份进行一些研究或发布更准确的信息(如您的帐户控制器代码)。

答案 2 :(得分:0)

通过用户管理器创建用户时,您可以应用一些自定义设置,其中一个需要一个唯一的电子邮件:

var um = new UserManager<User>(new UserStore<User>(new ApplicationDbContext()));
um.UserValidator = new UserValidator<User>(um)
{
    AllowOnlyAlphanumericUserNames = false,
    RequireUniqueEmail = false
};