In web api the default route is:
/api/locations/123?days=5
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
But what if I wanted the route to look like this /api/locations/123/events?days=5
while still being able to hit the LocationsController
with a route like this /api/locations/123?state=md
Controller:
public class LocationsController : ApiController {
// GET api/locations/123/events?days=5
public IEnumerable<Event> GetEventsByDays(int idLocation, int days) {
// do stuff
}
// GET api/locations/123?state=md
public IEnumerable<Location> GetLocationsByState(string state) {
// do stuff
}
}
There is really two questions here:
- Does it make sense to have a
LocationsController
that returns events or should there be a completely separate controller for that? - How would the route in the
WebApiConfig
be setup to allow for routes like this?
You can have a separate controller for events, if you would want to manipulate events independent of location. Please see if this is of help.
You're talking about two differents things :
Routing
Routing is used in ASP.NET MVC & Web Api to map URLs directly to a controller and/or an action. This is especially useful for readability, as the developer can focus on designing URLs that are human readable (for example, product support and search engine indexing). What is important here, is that there is no unique relation between a route and a controller. You can create 10 routes if you want that will map the same controller/action.
For example, your two routes can be like this
Also note that
/api/locations/123?state=md
is not correct for the default route template. It's/api/locations/123
. Because you have an extra parameter in the url, you will execute GetLocationsByState.Controller
It's recommanded to have a single responsiblity per controller and to keep it as small as possible. Your business logic should be somewhere else.
At the end, as you everything, you can do what you want without paying attention if it's good or bad. The difficulty is not always to setup an architecture but to maintain and to follow your own rules.
I hope this will help you. I suppose you are not so familliar with routing, so do not hesitate to read intro and action selection.