Mrg Gek Mrg Gek - 11 days ago 5
AngularJS Question

How to call specific get method from ASP.NET ApiController using Angularjs controller?

I have ApiController class that includes multiple GET methods.

//method 1
public IEnumerable<Drive> GetProducts()
{
...
}

//method2
public IEnumerable<string> GetCustomer(string name)
{
...
}

//method3
public IEnumerable<string> GetCustomers()
{
...
}


This is my angularjs script

var app = angular.module("MyApp", []);
app.controller("MyController", function ($scope, $http) {
$http.get('http://localhost:53551/api/values/GetProducts').
success(function (data, status, headers, config) {
$scope.strings = data;
}).
error(function (data, status, headers, config) {
alert("sa");
});
debugger;
$scope.open = function (name) {
debugger;
$http.get('http://localhost:53551/api/values/GetCustomer?' + name ).
success(function (data, status, headers, config) {
$scope.strings = data;
})
};
});


All functions only call GetProducts(). But I want to call each time a specific one.
Is it possible to call specific GET method through angularjs from ApiControler?

Answer

If you had DefaultWebAPI route registered as below

routes.MapHttpRoute(
    name: "API Default",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

then you just need to call method name /api/controllerName/actionName(don't need to mention HttpVerb in action name). The prefix before each action name indicates the nature of Action. I assumed you have ValuesController that has all above mentioned actions.

http://localhost:53551/api/values/customer
http://localhost:53551/api/values/products
http://localhost:53551/api/values/customers