Search code examples
asp.netasp.net-mvcentity-frameworkentity-framework-6linq-to-entities

Displaying User Full Name instead of User Email in AspNet MVC


I want to display a full name whenever a user logs in. Currently, I need a customize code that I work with because I am not using the identity method of getting the user logged in username.

Whenever I try using the supplied links, it either returns a null error or it displays nothing after it has logged in.

I have used the following links: https://www.codeproject.com/Tips/991663/Displaying-User-Full-Name-instead-of-User-Email-in

https://forums.asp.net/t/1848780.aspx?How+to+replace+User+Identity+Name+by+FirstName+Last+Name+at+login+time

public class ApplicationBaseController : Controller
{
    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (User != null)
        {
            var context = new mymodel();
            var username = User.Identity.Name;

            if (!string.IsNullOrEmpty(username))
            {
                var user = context.Users.SingleOrDefault(u => u.FirstName == username);
                string fullName = string.Concat(new string[] { user.FirstName, " ", user.LastName });
                ViewData.Add("FullName", fullName);
            }
        }
        base.OnActionExecuted(filterContext);
    }
    public ApplicationBaseController()
    { }
}


  <authentication mode="Forms">
      <forms cookieless="UseCookies" loginUrl="~/Account/Sigin" slidingExpiration="true"></forms>
  </authentication> 

Solution

  • A better way would be to at least implement some sort of ID system to reference the users insides what looks to be some sort of User class.

    mason explained it well that you will easily run into duplicate names and usernames very quickly. A common way to handle this is to attach an ID to a user. That way you can have multiples of the same name because you are just referencing them with an ID instead.

    Your lambda expression would end up looking something like: u => u.ID == passedInID