AngularJS WebApi Put - 不工作?

时间:2015-12-20 13:43:51

标签: c# angularjs asp.net-web-api asp.net-web-api2

我知道之前有人问过这个问题,而且我已经尝试过把它弄清楚了(并且失败了)。所以这是我的代码:

...
$resource("/SWDB/api/admin/users/:id", { id: "@id" },
        {
            update: {
                method: "PUT"
            }
        }
...

...
return AdminResource.users.update(params).$promise;
...

这就是我的更新调用方式:

$scope.params = {
        id: $stateParams.id,
        email: $scope.userservice.selectedUser.email,
        oldPassword: $scope.oldPassword,
        newPassword: $scope.newPassword,
        isLockoutEnabled: $scope.userservice.selectedUser.lockoutEnabled
    };

    $scope.userservice.updateUser($scope.params)
            .then(function() { $state.go("/"); }, function(error) { console.log(error) });

最后,这是我的控制器方法:

public async Task<HttpResponseMessage> Put(string id, string email, 
            string oldPassword, string newPassword, bool isLockoutEnabled)
        {
            var user = await _owinManager.UserManager.FindByIdAsync(id);
            if (user != null)
            {
                user.Email = email;

                if (!string.IsNullOrEmpty(oldPassword))
                {
                    if (_owinManager.UserManager.PasswordHasher.HashPassword(oldPassword) == user.PasswordHash)
                    {
                        if (!string.IsNullOrEmpty(newPassword))
                        {
                            user.PasswordHash = _owinManager.UserManager.PasswordHasher.HashPassword(newPassword);
                        }
                    }
                }

                var result = await _owinManager.UserManager.UpdateAsync(user);
                if (result.Succeeded)
                {
                    return new HttpResponseMessage(HttpStatusCode.Accepted);
                }
            }

            return new HttpResponseMessage(HttpStatusCode.InternalServerError);
        }

我一直得到:405,不允许。我试过POST,同样的事情。我的猜测是我正在拨打错误的电话......我只是不知道错误在哪里:(

1 个答案:

答案 0 :(得分:1)

我认为问题是因为Web API控制器定义了5个参数,但是,angularjs发送1(是的,一个复杂的参数),所以,在你的web api中将五个参数更改为复杂的参数,如下所示:

public class Test
{
    public string Id {get; set;}
    public string Email {get; set;}
    public string OldPassword {get; set;}
    public string NewPassword {get; set;}
    public bool IsLockoutEnabled {get; set;}
}

public async Task<HttpResponseMessage> Put(Test entity)
{
    .....
}