AngularJS无法找到$ http.delete目标

时间:2015-03-13 14:05:12

标签: c# angularjs

我有这个C#WebAPI 2项目:

[RoutePrefix("api/Account")]
public class AccountController : ApiController
{
    ....

    [HttpDelete]
    [Route("Delete")]
    public async Task<IHttpActionResult> Delete(string password)
    {
        // retrieve the authorized user's username
        // delete the authorized user using his password and username
    }

    ....
}

我的HTML表单:

  <form class="form-login span4 offset4 register-box" role="form">
    <h2 class="form-login-heading">Delete your account</h2>
    <h2 class="form-login-heading">Warning: this is permanent.</h2>
    <input type="password" class="form-control" placeholder="Password" data-ng-model="deleteConfirmPassword" required>
    <button class="btn btn-lg btn-info btn-block" type="submit" data-ng-click=" deleteAccount()">Delete</button>
</form>

使用的控制器:

app.controller('accountController', [
    '$scope', '$location', '$http', 'authService',
    function($scope, location, $http, authService) {

        $scope.deleteConfirmPassword = "";

        $scope.deleteAccount = function() {
            $http.delete(authService.serviceBase + 'api/account/Delete/', {
                password: $scope.deleteConfirmPassword
            }).success(function() {
                authService.logOut();
            }).
            error(function(response) {
                var errors = [];
                for (var key in response.data.modelState) {
                    for (var i = 0; i < response.data.modelState[key].length; i++) {
                        errors.push(response.data.modelState[key][i]);
                    }
                }
                $scope.message = "Failed to delete your account due to:" + errors.join(' ');
            });
        };
    }
]);

根据Firebug,调用了正确的URL,但似乎没有传递参数,我收到404错误。我在这段代码中做错了什么?

1 个答案:

答案 0 :(得分:1)

$http.delete()的第二个参数是配置对象,而不是数据对象,因此您需要将参数包装在另一个层中。此外,您的网址实际上不应包含“删除”。这由HTTP动词表示:

$http.delete(authService.serviceBase + 'api/account/', {
    data: { password: $scope.deleteConfirmPassword }
})