Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can ASP.NET Web API handle sub-resources with different controllers

Imagine a system with Users, Groups with corresponding ApiControllers. Then imagine following access patterns:

/api/users                  
/api/users/1
/api/users?groupId=1    <- #1 returns users belonging to group id 1 via Get(int? groupId)

/api/groups/
/api/groups/1
/api/groups/1/users     <- #2 sub resource, returns users belonging to group id 1

Is it possible to delegate responsibility of #2 to #1's Get(int? groupId) method? I'd like to keep responsibility of handling sub-resources with their original Controller. In another words, If a sub-resource also exists as resource then sub-resource handling should be? delegated to primary resource controller...

P.S. Now, I am not sure if the above approach is "cosher" with RESTfull styles, that is whole other discussion...

like image 295
zam6ak Avatar asked May 11 '12 15:05

zam6ak


People also ask

Which four types of methods does an API controller typically specify?

The four main HTTP methods (GET, PUT, POST, and DELETE) can be mapped to CRUD operations as follows: GET retrieves the representation of the resource at a specified URI.

What is the difference between API and controller?

The main difference is: Web API is a service for any client, any devices, and MVC Controller only serve its client. The same because it is MVC platform.

Which class should a controller in Web API be derived from?

Web API controller is a class which can be created under the Controllers folder or any other folder under your project's root folder. The name of a controller class must end with "Controller" and it must be derived from System. Web.


1 Answers

WEB Api Beta isn't supporting method level attribute for routing. They said, that are thinking of improving the routing story for the next release.

For now the only way (as i know) is to map explicitly those routes. In your case:

 // for your rest style api 
 routes.MapHttpRoute(
     name: "UserGroups",
     routeTemplate: "api/groups/{groupID}/users",
     defaults: new { controller = "Users"},
     constraints: new { groupID = @"\d+" } 
 );

and for RPC URI style the default route will work as glance.

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

And also you can override DefaultHttpControllerFactory class to create in your way instances of controllers.

Hope this help.

like image 78
s33sharp_94 Avatar answered Oct 26 '22 22:10

s33sharp_94