Search code examples
.net-coreasp.net-identity

Get Identity.Errors in controller with Identity Framework


In .net core with Identity, actually I have a service class UserService consuming the UserManager class and returning a User Class.

public UserService(UserManager<IdentityUser> userManager)
{
    _userManager = userManager;
}

In this class, I am creating an IdentityUser and I'm using the IdentityResult to get the query status. If I would have used the UserManager directly in my controller, I would do that in case of failure:

if (!result.Succeeded)
{
    return BadRequest(result.Errors);
}

The service class is returning a User, therefore I can't use an IdentityResult in my controller and I've lots result.Errors to put in the BadRequest.

How to catch this errors in the controller (to have it directly in the get request result)?


Solution

  • Finally I dealt with like that:

    Custom exception with custom property

    public UserServiceException(IEnumerable<IdentityError> errors)
    {
        Errors = errors;
    }
    

    then throw the custom exception in service class

    if (!result.Succeeded)
    {
        throw new UserServiceException(result.Errors);
    }
    

    And catch it in controller

    catch(UserServiceException ex)
    {
        return BadRequest(ex.Errors);
    }