c# - 访问用户属性的 ASP.NET Identity Extend 方法

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

因为我可以扩展方法来访问用户属性吗?

有如下方法:

User.Identity.GetUserId()
User.Identity.GetUserName()

哪些可以从 View 和 Controller 访问。

我想用如下方法扩展这个功能:

User.Identity.GetUserPhoneNumber()
User.Identity.GetUserLanguaje()

最佳答案

类似问题:Need access more user properties in User.Indentity Microsoft 专业人员在 codeplex worklog 中的回答如下

"You can get the User object and do User.Email or User.PhoneNumber since these properties are hanging off the User model"

我们可以在 ASP.Net 身份中获取应用程序当前的用户对象,如下所示,从那里您可以访问用户对象的所有属性,我们现在在 mvc5 网络应用程序中遵循相同的方法。

//In Account controller like this
var currentUser = UserManager.FindById(User.Identity.GetUserId());

在其他 Controller 中,您需要将以下内容添加到您的 Controller 中:

  var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));

  // Get the current logged in User and look up the user in ASP.NET Identity
  var currentUser = manager.FindById(User.Identity.GetUserId()); 

现在我们可以访问所有用户属性(电话号码和语言),如下所示

var phoneNumber = currentUser.PhoneNumber;
var userLanguage = currentUser.Language;

编辑:如果你想在任何 view.cshtml 或 _Layout.cshtml 中检索相同的内容,那么你应该像下面那样做

@using Microsoft.AspNet.Identity
@using Microsoft.AspNet.Identity.EntityFramework
@using YourWebApplication.Models

@{
    var phoneNumber= string.Empty;
    var userLanguage = string.Empty;
    if (User.Identity.IsAuthenticated) {
        var userStore = new UserStore<ApplicationUser>(new ApplicationDbContext());
        var manager = new UserManager<ApplicationUser>(userStore);
        var currentUser = manager.FindById(User.Identity.GetUserId());

        phoneNumber = currentUser.PhoneNumber;
        userLanguage = currentUser.Language;
    }
}

关于c# - 访问用户属性的 ASP.NET Identity Extend 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26836169/

相关文章:

c# - 在 EF Core 中自动填充 Created 和 LastModified

c# - 任何人都可以告诉这是什么类型的转换

c# - 我如何防止 Resharper 大量缩进 lambda?

javascript - jsonresult 数据集传递给另一个actionresult

.net - 将 ASP.Net Identity 表链接到用户详细信息表

c# - asp.net 身份 - SetPasswordHashAsync

c# - 使 Windows 服务像从特定用户运行一样运行

c# - 将依赖项注入(inject) ASP.NET MVC 3 操作过滤器。这种方法有什么问题?

javascript - MVC解析ajax到javascript excel

c# - ASP.NET Identity 的默认密码哈希器 - 它如何工作并且安全吗?