假设我们有一个BaseController,我们希望在其中实现一些通用功能(例如身份验证、授权等),并使其可用于所有派生的SubController。但是,在创建SubController时,我们也需要为它们实现独有的功能。
要做到这一点,我们可以使用Attribute路由和ASP.NET Core中的继承方式。我们可以为BaseController定义一个Controller属性路由,它到达控制器的根,并使用约定的路由(即[controller])。SubControllers可以从BaseController中继承Controller属性路由,并使用约定的路由。
以下是示例代码:
BaseController.cs:
[ApiController]
[Route("api/[controller]")]
public class BaseController : ControllerBase
{
// Add your common functionality here
}
SubController.cs:
public class SubController : BaseController
{
[HttpGet("{id}")]
public IActionResult Get(int id)
{
// Add your unique functionality here
}
}
在这里,SubController从BaseController中继承Controller属性路由,然后通过使用[id]参数为其特定的HTTP GET方法指定自己的路由。
此方法允许我们在所有SubControllers中使用通用代码,同时仍能够实现各自的功能。