I'm working on ASP.NET Core Webapi project. I would like to implement some kind of Base/Abstract generic controller for all methods that are common for every controller (e.g. CRUD methods) and inherit this Controller in all other controllers. I attach example code below:
public abstract class BaseApiController : Controller { [HttpGet] [Route("")] public virtual IActionResult GetAll() { ... } [HttpGet] [Route("{id}")] public virtual IActionResult GetById(int id) { ... } [HttpPost] [Route("")] public virtual IActionResult Insert(myModel model) { ... } } [Route("api/Student")] public class StudentController : BaseApiController { // Inherited endpoints: // GetAll method is available on api/Student [GET] // GetById method is available on api/Student/{id} [GET] // Insert method is available on api/Student [POST] // // Additional endpoints: // ShowNotes is available on api/Student/{id}/ShowNotes [GET] [HttpGet] [Route("{id}/ShowNotes")] public virtual IActionResult ShowNotes(int id) { ... } } [Route("api/Teacher")] public class TeacherController : BaseApiController { // Inherited endpoints: // GetAll method is available on api/Teacher [GET] // GetById method is available on api/Teacher/{id} [GET] // Insert method is available on api/Teacher [POST] // // Additional endpoints: // ShowHours is available on api/Teacher/{id}/ShowHours [GET] [HttpGet] [Route("{id}/ShowHours")] public virtual IActionResult ShowHours(int id) { ... } } I have seen this kind of solution in .NET Framework WebApi, with additional custom RouteProvider, e.g.:
public class WebApiCustomDirectRouteProvider : DefaultDirectRouteProvider { protected override IReadOnlyList<IDirectRouteFactory> GetActionRouteFactories(HttpActionDescriptor actionDescriptor) { return actionDescriptor.GetCustomAttributes<IDirectRouteFactory>(inherit: true); } } Every time I try to reach Endpoint in derived controller I got AmbiguousActionException:
Multiple actions matched. The following actions matched route data and had all constraints satisfied: XXX.WebApi.Controllers.CommonAppData.TeacherController.GetById XXX.WebApi.Controllers.CommonAppData.StudentController.GetById Is it possible to create such Base controller in .NET Core WebApi? How should I write it to reach Action Methods without declaring it explicitly in derived Controller? How should I configure this kind of solution? Any additional configuration in Startup class?