Search code examples
javascriptc#asp.net-web-apiasp.net-identity-2

How to get detailed errors from ModelState asp.net web api identity


I have a register form with asp.net web api 2 identity.

This is my register function:

// POST api/Account/Register
    [AllowAnonymous]
    [Route("Register")]
    public async Task<IHttpActionResult> Register(RegisterBindingModel model)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };

        IdentityResult result = await UserManager.CreateAsync(user, model.Password);

        if (!result.Succeeded)
        {
            return GetErrorResult(result);
        }

        try
        {
            ...send email
        }
        catch (Exception ex)
        {
            throw new Exception(ex.ToString());
        }
        return Ok();
    }

If ModelState is not valide it returns something like this:

enter image description here

How can I get this detailed error? I'm looking for a way to dynamically get all detailed errors from ModelState. I'm not sure if I should do it on the Web api or in javascript when I get the response.


Solution

  • I ended up writing the following function on my AccountController. It loops through the errors on the ModelState, adds them to a list and then it loops through the list and adds them to the ModelState.

    public void SetCustomError()
        {
            var errors = new List<string>();
            foreach (var state in ModelState)
            {
                foreach (var error in state.Value.Errors)
                {
                    errors.Add(error.ErrorMessage);
                }
            }
            foreach (var error in errors)
            {
                ModelState.AddModelError("CustomError", error);
            }
        }
    

    And then on my javascript I handled it like this:

    function showError(jqXHR) {
        if (jqXHR) {      
            jsonValue = jQuery.parseJSON(jqXHR.responseText);
            if (!jsonValue.modelState["customError"] == undefined) {
                $("#error").text(jsonValue.modelState["customError"][0]);
            }
            else {
                $("#error").text(jsonValue.modelState[""][0]);
            }
            $("#modalError").dialog();
        }
    }