3

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 "";
    }
}
Community
  • 1
  • 1
  • please help me im new on this – marcelo sanchez Dec 02 '14 at 19:58
  • An Extension Method is a static method that looks like it belongs to a class. In this case, you could do something like `objectThatImplementsIPrincipal.FullName()`, which will have the exact same outcome than executing `FullName(objectThatImplementsIPrincipal)`. I'm afraid you need to read some guides on Extension Methods first. – Andrew Dec 02 '14 at 19:59
  • on this pages i found the same but i dont know where put the extension method [link1](http://stackoverflow.com/questions/21362751/user-identity-name-full-name-mvc5), [link2](http://forums.asp.net/t/1957500.aspx?How%20to%20access%20custom%20Identity%20or%20ApplicationUser%20properties%20) – marcelo sanchez Dec 02 '14 at 20:03
  • 1
    The extension method can be anywhere in your solution. It can simply be another file in the project, even sharing the namespace. Did you do some research about them? http://msdn.microsoft.com/en-us/library/bb383977.aspx – Andrew Dec 03 '14 at 00:01

1 Answers1

1
  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

Melody Magdy
  • 148
  • 3
  • 11