Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension Method on Identity

im using MVC 5 and i found this : User.Identity.Name full name mvc5 , but i dont know how use the "Extension Method on Identity" where i put this code, and where...please help me

Extension Method on Identity:

public static class GenericPrincipalExtensions
{
    public static string FullName(this IPrincipal user)
    {
        if (user.Identity.IsAuthenticated)
        {
            ClaimsIdentity claimsIdentity = user.Identity as ClaimsIdentity;
            foreach (var claim in claimsIdentity.Claims)
            {
                if (claim.Type == "FullName")
                    return claim.Value;
            }
            return "";
        }
        else
            return "";
    }
}
like image 534
marcelo sanchez Avatar asked Feb 26 '26 13:02

marcelo sanchez


1 Answers

  1. Create a new static class, for example IdentityExtended
  2. Put static method inside it, for example
  3. Put the namespaces of Clamis and Principal

using System.Security.Claims; using System.Security.Principal;

public static class IdentityExtended { public static string GetFullName(this IIdentity identity) { IEnumerable<Claim> claims = ((ClaimsIdentity)identity).Claims; var FullName = claims.Where(c => c.Type == "FullName").SingleOrDefault(); return FullName.Value; } }

  1. Inside View for Example write as below

    <h1 class="display-4 rainbow-text">Hello, @User.Identity.GetFullName()!</h1>

    Just make sure you put the class inside solution itself no inside a subfolder

like image 93
Melody Magdy Avatar answered Mar 03 '26 03:03

Melody Magdy