我正在开发ASP.NET Core Webapi项目。我想实现一种基础/抽象的通用控制器,用于所有常见控制器的方法(例如CRUD方法),并在所有其他控制器中继承此控制器。
以下是示例代码:
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)
{
...
}
}
我曾在.NET Framework WebApi中见过这种解决方案,还有自定义的RouteProvider,例如:
public class WebApiCustomDirectRouteProvider : DefaultDirectRouteProvider
{
protected override IReadOnlyList<IDirectRouteFactory> GetActionRouteFactories(HttpActionDescriptor actionDescriptor)
{
return actionDescriptor.GetCustomAttributes<IDirectRouteFactory>(inherit: true);
}
}
每次我尝试在派生控制器中访问端点时,都会出现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
是否可以在.NET Core WebApi中创建这样的基本控制器? 我应该如何编写它以在派生控制器中不需要显式声明即可到达Action方法? 我应该如何配置此类解决方案?在Startup类中需要进行任何其他配置吗?
WebApiCustomDirectRouteProvider
。 - Roman Marusyk