c# - ASP Net Core - 如何进行多级路由继承?

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

我正在开发 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/regionsGET方法,但它是/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/

相关文章:

c# - 仅当 listView 不为空时,如何才能激活/启用 contextmenustrip 菜单?

c# - 如何关闭其子窗口的父窗口?

c# - C# 在图像中绘制一个点

使用 Serilog 进行 Azure 函数日志记录到 Application Insights

c# - 如何将 .NET 框架中的 gRPC 客户端与安全的 .NET Core 服务器连接?

C# 列表框项目双击事件

javascript - ReactJS:net::ERR_HTTP2_PROTOCOL_ERROR 200 与 .NetCore 在 HTTPS

asp.net-core - .NET Core MVC 页面更改后不刷新

c# - 用MediatR替换服务层-值得这样做吗?

.net-core - MassTransit 故障处理配置