1

How can i get error message returned by web api in Angular.

This is what I have got in fiddler

{"Message":"The request is invalid.","ModelState":{"":["Name test1 is already taken."]}}

 ()''

what do i change in error function to show just 'Name test1 is already taken'? This is Angular http post.

        $http({
            method: 'POST',
            url: 'api/Account/Register',
            data: { 'UserName': user.username, 'Password': user.password, 'ConfirmPassword': user.confirmpassword, 'Email': user.email },
        })
        .success(function () {
            toastr.success('successfully registered. ');                        
        })
        .error(function (error) {           
            toastr.error('error:' + error);                
        });

3 Answers 3

1

The response you get from the server is quite surprising. It does not look like a valid json string. the first item in model state has no id.

{"Message":"The request is invalid.","ModelState":{"":["Name test1 is already taken."]}}

should be something like:

{"Message":"The request is invalid.","ModelState":{"message":["Name test1 is already taken."]}}

and then you could access to your message with

error.ModelState.message[0]

It should work, although the error response look too complicated. Why is the error message in an array? Isn't it possible to simplify the response like this:

{"Message":"The request is invalid.","ModelState":{"message":"Name test1 is already taken."}} 

or

{"Message":"The request is invalid.","ModelState": "Name test1 is already taken."} 

Or if you need several error messages to be returned at once:

{"Message":"The request is invalid.","ModelState": ["Name test1 is already taken."]}  

In this last example you could access the messages by iterating on error.ModelStage

0
1
ModelState[""][0] 

that will give you just the message

0

This code has worked for me:

$scope.message = response.statusText + "\r\n";
if (response.data.modelState) {
    for (var key in response.data.modelState) {
        $scope.message += response.data.modelState[key] + "\r\n";
    }
}
if (response.data.exceptionMessage)
    $scope.message += response.data.exceptionMessage;

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.