AngularJS WebApi Put - not working?

I know it's been asked before, and I've tried figuring it out myself (and failed). So here's my code:

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

And

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

This is how my update is called:

$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) });

And finally, this is my controller method:

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);
        }

I keep getting: 405, not allowed. I tried POST, same thing. My guess is I am making an erroneous call... I just don't know where the error is :(

Upvotes: 1

Views: 90

Answers (1)

Julito Avellaneda
Julito Avellaneda

Reputation: 2385

I think the problem is because the Web API Controller define 5 params, but, angularjs is sending 1 (yes, a complex parameter), so, in your web api change the five params to a complex parameter like this:

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)
{
    .....
}

Upvotes: 1

Related Questions