Asp.Net Web窗体访问母版页上的用户自定义属性



如果Web窗体项目使用Asp.Net标识系统,我如何访问母版页上的自定义用户属性(例如名字、姓氏)?我已经做了这些配置http://www.itorian.com/2013/11/customize-users-profile-in-aspnet.html但我的项目不是MVC而是Web窗体。

默认情况下,我只能使用访问用户名

Context.User.Identity.GetUserName()

没关系,我已经找到了答案。

在Site.Master.cs上添加以下行:

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Owin;
using EvSiProject.Models;
using Microsoft.AspNet.Identity.EntityFramework;

然后在Page_Load()函数上添加以下行:

    if (Context.User.Identity.IsAuthenticated)
    {
        var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
        var currentUser = manager.FindById(Context.User.Identity.GetUserId());
        //string fName = currentUser.FirstName;
        //string lName = currentUser.LastName;
    }

就是这样。

只是在Ceparu的答案中加上我的两美分:

在Site.Master.cs中,我还添加了一个公共字段

public ApplicationUser CurrentUser;

在Page_Load()函数中,将第二行更改为使用公共字段

CurrentUser = manager.FindById(Context.User.Identity.GetUserId());

更改Site.Master.cs后,在Site.Master中可以使用

<%: CurrentUser.FirstName %>

代替

<%: Context.User.Identity.GetUserName()  %>

完成!

最新更新