繁体   English   中英

自定义@ User.Identity.NewMethodHere()以使用ef代码开头和asp.net mvc返回用户的名字和姓氏

[英]Customize @User.Identity.NewMethodHere() to return a user first and last name, using ef code first and asp.net mvc

我什至不知道该如何措辞...

我正在使用最新的asp.net身份提供程序。 我希望能够从我网站的几乎每个视图上从登录用户中提取某些数据。 我的简化模型是这样的:

User.cs

public class User : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    ....
}

在剃刀视图中,我得到检查是否有人登录,然后使用:

@User.Identity.GetUserId()

这显然会返回我的用户名。 我想提出一种方法,可以调用@ User.Identity.GetUserFirstAndLastName()或类似的方法。 有没有办法添加这样的电话? 我真的很讨厌必须为ViewBag提供每个视图的值。

感谢wdosanjos向我指出了扩展方法。 阅读链接并进行更多搜索之后,我想到了:

public static class IdentityApplicationUserExtension
{
    public static User GetApplicationUser(this IIdentity identity)
    {
        var manager = new UserManager<User>(new UserStore<User>(new MyDbContext()));
        return manager.FindById<User>(identity.GetUserId());
    }
}

用户是ApplicationUser类。

在剃刀视图中,我所需要做的就是:

 @User.Identity.GetApplicationUser().AnyColumnFieldHere

毕竟超级简单!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM