I may have a lame question, but I am struggling a bit with routing of multiple controllers in one Url. So my question is how to work with a url like this:
GET http://foo.com/API/Devices/2/Parameters/2
where eventually device
and parameters
are all controllers and numbers are Ids. I have controllers for each of them but how do process them, route them to proper controller?
Any direction to look at?
UPDATE:
Just for clarification the solution which I ended up using and follows the answer below.
Routing snippet:
config.Routes.MapHttpRoute(
name: "DeviceCommandsControllerHttpRoute",
routeTemplate: "api/devices/{deviceId}/commands/{id}",
defaults: new { controller = "devicecommands", id = RouteParameter.Optional }
);
Controller snippet:
[HttpGet]
public DeviceCommand GetById(int id, int deviceId)
{ ... }
and finally the URL:
GET http://localhost:49479/api/Devices/2/Commands/1
Yes, It is possible to share a view across multiple controllers by putting a view into the shared folder. By doing like this, you can automatically make the view available across multiple controllers.
In Spring MVC, we can create multiple controllers at a time. It is required to map each controller class with @Controller annotation.
You can also write multiple routes onthe same action or controller. For example if you want to call Contact action method with /Home/contact url just write the [Route("home/contact")] on action method.
"Routes" to forward the supported requests (and any information encoded in request URLs) to the appropriate controller functions. Controller functions to get the requested data from the models, create an HTML page displaying the data, and return it to the user to view in the browser.
I am working with a smilar need right now and I have the following route structure:
public static void RegisterRoutes(HttpRouteCollection routes) {
routes.MapHttpRoute(
"UserRolesHttpRoute",
"api/users/{key}/roles",
new { controller = "UserRoles" });
routes.MapHttpRoute(
"AffiliateShipmentsHttpRoute",
"api/affiliates/{key}/shipments",
new { controller = "AffiliateShipments" });
routes.MapHttpRoute(
"ShipmentStatesHttpRoute",
"api/shipments/{key}/shipmentstates",
new { controller = "ShipmentStates" });
routes.MapHttpRoute(
"AffiliateShipmentShipmentStatesHttpRoute",
"api/affiliates/{key}/shipments/{shipmentKey}/shipmentstates",
new { controller = "AffiliateShipmentShipmentStates" });
routes.MapHttpRoute(
"DefaultHttpRoute",
"api/{controller}/{key}",
new { key = RouteParameter.Optional });
}
I think you can sort of figure out how you can implement yours based on this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With