Asp.Net Web Forms access user custom properties on

2019-09-06 09:43发布

How can I access custom user properties(eg. first name, last name) on the master page if the Web Forms Project is using Asp.Net Identity System? I've already made this configurations http://www.itorian.com/2013/11/customize-users-profile-in-aspnet.html but my project is not MVC is Web Forms.

By default I can only access user's name using:

Context.User.Identity.GetUserName()

2条回答
Anthone
2楼-- · 2019-09-06 10:23

Never mind, I've found the answer.

On Site.Master.cs add this lines:

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

Then add this lines on the Page_Load() function:

    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;
    }

And that's it.

查看更多
孤傲高冷的网名
3楼-- · 2019-09-06 10:49

Just to add my two cents to Ceparu's answer:

In Site.Master.cs I also added a public field

public ApplicationUser CurrentUser;

In the Page_Load() function changed the second line to use the public field

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

After changing Site.Master.cs, in Site.Master you can use

<%: CurrentUser.FirstName %>

Instead of

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

Done!

查看更多
登录 后发表回答