Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 (e.g. 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?

like image 602
Minja Avatar asked Jul 15 '16 16:07

Minja


1 Answers

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);
}
like image 164
Igor Avatar answered Oct 26 '22 13:10

Igor