简体   繁体   中英

Asp .Net Identity - Custom IUserStore FindByNameAsync method

I want to override IUserStore FindByNameAsync method. Method is used in CreateAsync method of UserManager class. If I return IdentityUser instance from the method, it works fine, but if I return null (eg there is no user with that username) I got:

{"Message":"An error has occurred.","ExceptionMessage":"Object reference not set to an instance of an object.","ExceptionType":"System.NullReferenceException","StackTrace":" at Microsoft.AspNet.Identity.UserValidator`2. ValidateUserName d__4.MoveNext()

This is my override method

public Task<MyUser> FindByNameAsync(string userName)
{
    return null;
}

I think it fails in UserValidator class - ValidateUserName method in code snippet below.

else
{
    var owner = await Manager.FindByNameAsync(user.UserName).WithCurrentCulture();
    if (owner != null && !EqualityComparer<TKey>.Default.Equals(owner.Id, user.Id))
    {
        errors.Add(String.Format(CultureInfo.CurrentCulture, Resources.DuplicateName, user.UserName));
    }
}

What to return from FindByNameAsync method to avoid this exception?

You have to still return a Task in your code, see the change below. This is because the callers expects a Task and the result in the Task is what you want to return as having a null value. By returning null directly the caller's attempt to unwrap the task (through await or Task.Result ) fails which generates the NullReferenceException .

public Task<MyUser> FindByNameAsync(string userName)
{
    return Task.FromResult((MyUser)null);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM