在控制器上找不到与AngularJS和Asp.Net WebApi请求匹配的操作

时间:2015-10-13 05:06:05

标签: ajax angularjs asp.net-web-api2 asp.net-web-api-routing

我的头是冒烟的。我正在使用Asp.Net Web Api学习AnjularJS。我有以下AnjularJS控制器,它具有对Web Api服务的ajax调用,如下所示。

CustomerController = function ($http, $scope, $httpParamSerializer) {
    $scope.modelObject = { first: 2, second: 3 };       
    $scope.modelObject.sendRequest = function (requestType) {
        var dataTemp = {first:2, second:3 };
        alert( $httpParamSerializer(dataTemp));
        $http({
            method: 'GET',
            url: '/api/bindings/sumnumbers',
            data: $httpParamSerializer(dataTemp),
            headers: { 'Content-Type': 'application/json' }
        }
        ).then(function successCallback(response) {
            $scope.modelObject.result = response.data;
        }, function errorCallback(response) {
            alert(response.data);
            $scope.modelObject.result = response;
        });
    }

web api动作方法如下。

    [HttpGet]
    [HttpPost]
    public int SumNumbers(int first, int second)
    {
        return first + second;
    }

我甚至在webconfig的webconfig中有一条路线,如教程中所建议的那样。

        config.Routes.MapHttpRoute(
            name: "Binding Example Route",
            routeTemplate: "api/{controller}/{action}/{first}/{second}"
        );

但是我收到以下错误

{"data":{"Message":"No HTTP resource was found that matches the request URI        'http://localhost:29845/api/bindings/sumnumbers'.","MessageDetail":"No action was found on the controller 'Bindings' that matches the request."},"status":404,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"url":"/api/bindings/sumnumbers","data":"first=2&second=3","headers":{"Content-Type":"application/json","Accept":"application/json, text/plain, */*"}},"statusText":"Not Found"}

有人可以建议我怎么了?

2 个答案:

答案 0 :(得分:2)

我建议使用属性路由来简化操作。您可以将WEB API方法更改为:

[HttpGet]
[Route("api/bindings/sumnumbers/{first}/{second}")]
public int SumNumbers([FromUri] int first, [FromUri] int second)
{
    return first + second;
}

在Angular JS Controller中,您需要传递URL中的参数:

url: '/api/bindings/sumnumbers/' + first + '/' + second

这对你有用。我还强烈建议使用像Fiddler这样的工具来测试你的WEB API方法,然后再用Angular进行测试。

答案 1 :(得分:0)

刚刚找到,而不是

data: $httpParamSerializer(dataTemp),

在ajax调用中,你可以简单地拥有

params: dataTemp,

然后在这种情况下你不需要为action方法设置一个route属性,而为keithm建议的参数设置FromUi属性。