首页 > 解决方案 > 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 控制器?我应该如何编写它以达到操作方法而不在派生控制器中显式声明它?我应该如何配置这种解决方案?启动类中的任何其他配置?

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

解决方案


推荐阅读