ASP.NET Identity Is default ApplicationUserManager

2019-07-10 16:49发布

问题:

Hello,

I was looking into ASP.NET Identity source, particulary, in UserValidator. I wanted to rewrite it for my own project, to be able to change error messages. So I copy that class into my project. When I try to use it - I get an error - 'Microsoft.AspNet.Identity.UserManager<TUser,TKey>' does not contain a definition for 'GetEmailStore' and no extension method 'GetEmailStore' accepting a first argument of type 'Microsoft.AspNet.Identity.UserManager<TUser,TKey>' could be found (are you missing a using directive or an assembly reference?) at this line

var email = await Manager.GetEmailStore().GetEmailAsync(user).ConfigureAwait(false);

My question is - how can this work in AspNet.Identity framework, but not in my project? It doesn't look like that Manager is implementing IUserEmailStore.

All I tested, was default MVC template in VS2013

回答1:

I finally found the answer (after searching a lot).

If you see the UserManager's source code, the GetEmailStore() method does exist, but is internal. Take a look:

    internal IUserEmailStore<TUser, TKey> GetEmailStore()
    {
        var cast = Store as IUserEmailStore<TUser, TKey>;
        if (cast == null)
        {
            throw new NotSupportedException(Resources.StoreNotIUserEmailStore);
        }
        return cast;
    }

So, it exists only inside files of the own Identity assembly, that's why it works there and not in your code.

Moreover, you can achieve the same result as follow:

var email = await Manager.GetEmailAsync(user.Id).ConfigureAwait(false);

Click here to see UserManager's Source Code