Skip to content

Instantly share code, notes, and snippets.

@jayharris
Created September 24, 2013 13:09
Show Gist options
  • Save jayharris/6684483 to your computer and use it in GitHub Desktop.
Save jayharris/6684483 to your computer and use it in GitHub Desktop.
Register WebAPI Routes with multiple nested segments
public class CountryController : ApiController {
public IEnumerable<CountryResponseModel> Get() {
// Logic
return model;
}
public CountryResponseModel Get(int id) {
// Logic
return model;
}
public CountryResponseModel Post([FromBody] CountryRequestodel value) {
// Logic
return model;
}
public CountryResponseModel Put(int id, [FromBody] CountryRequestodel value) {
// Logic
return model;
}
public CountryResponseModel Delete(int id) {
// Logic
return model;
}
}
public class CountyController : ApiController {
public IEnumerable<CountyResponseModel> Get(int countryId, int stateId) {
// Logic
return model;
}
public CountyResponseModel Get(int countryId, int stateId, int id) {
// Logic
return model;
}
public CountyResponseModel Post(int countryId, int stateId, [FromBody] CountyRequestodel value) {
// Logic
return model;
}
public CountyResponseModel Put(int countryId, int stateId, int id, [FromBody] CountyRequestodel value) {
// Logic
return model;
}
public CountyResponseModel Delete(int countryId, int stateId, int id) {
// Logic
return model;
}
}
public class StateController : ApiController {
public IEnumerable<StateResponseModel> Get(int countryId) {
// Logic
return model;
}
public StateResponseModel Get(int countryId, int id) {
// Logic
return model;
}
public StateResponseModel Post(int countryId, [FromBody] StateRequestodel value) {
// Logic
return model;
}
public StateResponseModel Put(int countryId, int id, [FromBody] StateRequestodel value) {
// Logic
return model;
}
public StateResponseModel Delete(int countryId, int id) {
// Logic
return model;
}
}
public static class WebApiConfig {
public static void Register(HttpConfiguration config) {
RegisterRoutes(config.Routes);
}
public static void RegisterRoutes(HttpRouteCollection routes) {
routes.MapHttpRoute(name: "County_API",
routeTemplate: "api/Countries/{countryId}/State/{stateId}/County/{id}",
defaults:
new {
countryId = RouteParameter.Optional,
stateId = RouteParameter.Optional,
controller = "County",
id = RouteParameter.Optional
});
routes.MapHttpRoute(name: "State_API",
routeTemplate: "api/Countries/{countryId}/State/{id}",
defaults:
new {
countryId = RouteParameter.Optional,
controller = "State",
id = RouteParameter.Optional
});
routes.MapHttpRoute(name: "Base_API",
routeTemplate: "api/{controller}/{id}",
defaults:
new {
controller = "Countries",
id = RouteParameter.Optional
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment