Wednesday, April 9, 2014

Muliple Get, Put, Post, Delete under Web API calls to same Controller from Angular JS

In the example mentioned below , you could define multiple PUT to same Web API controller

1. Use Microsoft ASP.Net Web API 2.1 instead of older versions.
2. On application start in global asax add the Routes  ( .cs) :

public static void Register(HttpConfiguration configuration)
{
configuration.MapHttpAttributeRoutes();
var routes = configuration.Routes;
configuration.EnsureInitialized();
}


3. Define the Route on the functions in Controller ( .cs) :

[Route("api/User/{id}/ActUserNow")]
[HttpPut]
public GeneralResponse ActUser(int id)
{ ........}


4. Define App.factory in Angular like ( js side) :

App.constant('settings', {
baseurl: "",
apiurl: "api/"
});


// observe in the code below how id is variable coming from function calls and action is in model resource factory

App.factory('myserviceApi', ['$resource', 'settings', function ($resource, settings) {
return $resource(settings.apiurl + ':controller/:id/:action', {id: '@id'}, {
ProcessUser: { method: 'PUT', isArray: false, params: { controller: 'User', action:'ActUserNow', 'noCache': Math.random() } }


});
}]);

5. Method call in Angular js controller like  ( js side)  :


ProcessLastUser: function (Id) {
if (Id != null && Id != '') {
var param = { id: Id };
myserviceApi.ProcessUser(param, function (res) { ............ });},

No comments:

Post a Comment