0

I have a problem to get response from my API-controller from my factory.

I get error 404 page not found.

I got the right .js-file in the HTML-document and the routing seems fine.

App.js:

module.factory('userFactory', function($http) {
return {
    getFormData: function(callback) {
        $http.get('/api/GetMessage').success(callback);
    }
  }
});

module.controller("messageController", function($scope, userFactory) {
  $scope.getMessage = function() {
    userFactory.getFormData(function(results) {
        $scope.text = results;
    });
  }
});

API-controller:

using System.Web.Http;

namespace kittyChatt.Backend.Controllers {
public class GetMessageController : ApiController
{
    public object Get()
    {
        object obj = "hello world";        
        return obj;
    }
  }
}

I want the hello world to show whene i hit a button in my view.

View:

   <div>
     <button ng-click="getMessage()">Get my message</button>
      <p>{{text}}</p>
   </div>

Plz help!

tod
  • 1,539
  • 4
  • 17
  • 43
Johan Byrén
  • 890
  • 2
  • 13
  • 28

2 Answers2

2
return {
   getFormData: function(callback) {
      $http.get('/api/GetMessage/Get').success(callback);
   }
}

You forgot to tell wich action in your controller you wanted to call.

By default, actions are HttpPost(yeah I know, I wrote HttpGet, which was the case in asp.net mvc), but I'd suggest you to still decorate the method with the correct verb :

[HttpGet]
public object Get()
{
    object obj = "hello world";        
    return obj;
}

Edit, which has absolutely no link with the first question :
quoted from asp.net documentation :

  • You can specify the HTTP method with an attribute: AcceptVerbs, HttpDelete, HttpGet, HttpHead, HttpOptions, HttpPatch, HttpPost, or HttpPut.
  • Otherwise, if the name of the controller method starts with "Get", "Post", "Put", "Delete", "Head", "Options", or "Patch", then by convention the action supports that HTTP method.
  • If none of the above, the method supports POST.

But, I still think it's a good practice to always decorate actions with the verb on top of it. That kind of practice should avoid useless discussions ;-)

Deblaton Jean-Philippe
  • 11,188
  • 3
  • 49
  • 66
1

Is the route path of your api correct?

Into the configuration you must write something like this:

public static void Register( HttpConfiguration config )
{
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { action = RouteParameter.Optional, id =   RouteParameter.Optional }
            );
}
ADIMO
  • 1,107
  • 12
  • 24