Search code examples
ajaxangularjsasp.net-web-api2asp.net-web-api-routing

No action was found on the controller that matches the request from AngularJS and Asp.Net WebApi


My head is fuming. I am learning AnjularJS with Asp.Net Web Api. I have the following AnjularJS controller which has an ajax call to a Web Api service as follows.

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

And the web api action method is as follows.

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

I even have a route in the webconfig for web api as follows as was suggested in the tutorial.

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

But I get the following error

{"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"}

Can some one please suggest me whats wrong?


Solution

  • I would recommend using Attribute Routing to make things easier. You could change your WEB API method to this:

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

    In your Angular JS Controller you need to pass the parameters in the URL:

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

    This should work for you. I would also highly recommend using a tool like Fiddler to test your WEB API methods before trying them out with Angular.