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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With