我正在开发 API,但遇到以下问题
我有抽象的ApiController,像这样
public abstract class ApiController<TService> : ApiController
where TService : BaseService
{
#region Fields
/// <summary>
/// Data manager
/// </summary>
protected TService Service { get; } = ServiceCollectionHelper.GetElementFromDependencyInjection<TService>();
#endregion
#region Constructors
#endregion
}
[ApiController]
[Authorize]
[Produces("application/json")]
[Route("api", Name = "BaseApiRoute")]
public abstract class ApiController : ControllerBase
{
}
我有多个 Controller ,它们继承ApiController<TService>
,或ApiController
.
示例 Controller :
[Route("[controller]")]
public class RegionsController : ApiController<RegionService>
{
#region Fields
#endregion
#region Constructor
#endregion
#region Methods
/// <summary>
/// Get the regions
/// </summary>
/// <param name="includeDepartments">Include the region departments</param>
/// <returns>Regions</returns>
[HttpGet]
[ProducesResponseType(typeof(IEnumerable<DepartmentDTO>), StatusCodes.Status200OK)]
public async Task<ActionResult<IEnumerable<RegionDTO>>> GetAsync(bool includeDepartments = false)
{
return this.Ok(await this.Service.GetAsync(includeDepartments));
}
#endregion
}
通常,方法 RegionsController.GetAsync
的路由应该是/api/regions
与 GET
方法,但它是/regions
为什么继承不起作用,以及如何纠正它以获得 /api
所有路由的前缀?
我尝试替换 [Route("/api")]
与 [Area("/api')]
但没有成功。
谢谢
最佳答案
如果您在 RegionsController
上定义 [Route("[controller]")]
,它将覆盖基本路由。
相反,您可以在基本 Controller 上使用 token 替换来定义路由,例如:
[ApiController]
[Authorize]
[Produces("application/json")]
[Route("api/[controller]", Name = "BaseApiRoute_[controller]")]
public abstract class ApiController : ControllerBase
{
}
参见token replacement and route inheritance了解更多信息。
Attribute routes can also be combined with inheritance. This is powerful combined with token replacement. Token replacement also applies to route names defined by attribute routes.
关于c# - ASP Net Core - 如何进行多级路由继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61456537/