c# - ASP.NET Core 控制器路由属性继承和抽象控制器操作 - AmbiguousActionException
问题描述
我正在开发 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 中创建这样的 Base 控制器?我应该如何编写它以达到操作方法而不在派生控制器中显式声明它?我应该如何配置这种解决方案?启动类中的任何其他配置?
解决方案
推荐阅读
- url - Google 列出了后缀为“?from=xiaodiaomao.com”的网站
- javascript - 在循环中如何引用主要的“this”?
- macos - 如何通过 HDMI 在 Macbook Pro 2017 上运行 4K 60 Hz
- string - 使用 Liquid 连接字符串
- openlayers - arcmap 10.6 shapefile 不显示在 OpenLayers 4.6.5 中
- elasticsearch - 查找 lucene 中匹配文档的出现次数
- asp.net-core - 创建自定义 Auth0 登录页面
- ios - ECDSA secp256k1 密钥对生成和在 Swift 上签名
- php - 如何使用 $_POST 或 $_GET 根据 HTML 表单过滤数据
- php - 来自sqlite参考中的php函数的变量