ASP.NET核心控制器路由属性继承和抽象控制器操作-AmbiguousActionException

时间:2018-11-26 20:02:05

标签: c# asp.net asp.net-core .net-core asp.net-core-webapi

我正在研究ASP.NET Core Webapi项目。我想为每种控制器通用的所有方法(例如CRUD方法)实现某种Base / Abstract通用控制器,并在所有其他控制器中继承此Controller。 我在下面附上示例代码:

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);
    }
}

每次尝试在派生控制器中到达Endpoint时,我都会得到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控制器? 我应该如何编写它才能到达Action Methods,而无需在派生Controller中显式声明它? 我应该如何配置这种解决方案?启动类中是否还有其他配置?

0 个答案:

没有答案
相关问题