加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何向客户端呈现错误? AngularJS / WebApi ModelState

发布时间:2020-12-17 07:38:35 所属栏目:安全 来源:网络整理
导读:我正在为后端构建一个带有WebApi的AngularJS SPA应用程序.我在服务器上使用模型验证的属性,如果验证失败,这是我从ModelState返回的. {"Message":"The request is invalid.","ModelState":{"model.LastName":["Last Name must be at least 2 characters long.
我正在为后端构建一个带有WebApi的AngularJS SPA应用程序.我在服务器上使用模型验证的属性,如果验证失败,这是我从ModelState返回的.
{"Message":"The request is invalid.","ModelState":{"model.LastName":["Last Name must be at least 2 characters long."]}}

如何使用AngularJS将其呈现给客户端?

//Save User Info
    $scope.processDriverForm = function(isValid) {
        if (isValid) {
            //set button disabled,icon,text
            $scope.locked = true;
            $scope.icon = 'fa fa-spinner fa-spin';
            $scope.buttonText = 'Saving...';
            $scope.submitted = true;
            $scope.formData.birthDate = $scope.formData.birthMonth + '/' + $scope.formData.birthDay + '/' + $scope.formData.birthYear;
            $http({
                    method: 'POST',url: 'api/Account/Register',data: $.param($scope.formData),headers: { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
                })
                .success(function (data) {
                    console.log(data);
                    toastr.success('User ' + $scope.formData.username + ' created!');
                    $scope.userForm.$setPristine();
                    $scope.formData = {};
                    //reset the button
                    $scope.locked = false;
                    $scope.icon = '';
                    $scope.buttonText = 'Save';
                    //reset validation submitted
                    $scope.submitted = false;
                })
                .error(function (data,response) {
                    console.log(data);
                    toastr.error('Ooops! There was an error creating the user. Try again and if the problem persists,contact Support.');
                    //reset the button
                    $scope.locked = false;
                    $scope.icon = '';
                    $scope.buttonText = 'Save';
                    $scope.submitted = false;

                    var resp = {};

                    var errors = [];
                    for (var key in resp.ModelState) {
                        for (var i = 0; i < resp.ModelState[key].length; i++) {
                            errors.push(resp.ModelState[key][i]);
                        }
                    }
                    $scope.errors = errors;

                });

        }
        else {
            toastr.warning('Invalid User Form,correct errors and try again.');
        }
    };
当你打电话给你的服务器时,根据拒绝的$http承诺捕获错误.

然后在您的控制器中,我将建议在处理显示错误时将响应平坦化为一系列错误,如fiddle example所示:

for (var key in resp.ModelState) {
    for (var i = 0; i < resp.ModelState[key].length; i++) {
        errors.push(resp.ModelState[key][i]);
    }
}

把它放在一起:

// Post the data to the web api/service
$http.post(url,data)
    .success(successHandler)
    .error(function (response) {
        // when there's an error,parse the error
        // and set it to the scope (for binding)
        $scope.errors = parseErrors(response);
    });

//separate method for parsing errors into a single flat array
function parseErrors(response) {
    var errors = [];
    for (var key in response.ModelState) {
        for (var i = 0; i < response.ModelState[key].length; i++) {
            errors.push(response.ModelState[key][i]);
        }
    }
    return errors;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读