Search code examples
c#asp.net-mvcextension-methodsmembership-provideriidentity

Extension of IIdentity


I'm trying to use the exention method for IIdentity

Here is my class:

public static class MyIdentity 
{
    public static string FullName(this IIdentity identity)
    {
        return "John Doe";
    }
}

and I'm trying to use it on my view like this:

@Context.User.Identity.FullName()

but I get the following error:

'System.Security.Principal.IIdentity' does not contain a definition for 'FullName' and no extension method 'FullName' accepting a first argument of type 'System.Security.Principal.IIdentity' could be found


Solution

  • Make sure you've brought the namespace in which this extension method is defined into scope in your view:

    @using NameSpaceInWhichTheMyIdentityStaticClassIsDefined
    @User.Identity.FullName()
    

    or if you want to use it in many views to avoid adding this namespace in each view you could also add it to the <namespaces> section of ~/views/web.config (Not to be confused with ~/web.config):

    <add namespace="NameSpaceInWhichTheMyIdentityStaticClassIsDefined" />