C# 如何在不同的控制器中设置相同的路由模板

C# 如何在不同的控制器中设置相同的路由模板,c#,asp.net-core,.net-core,routes,asp.net-core-webapi,C#,Asp.net Core,.net Core,Routes,Asp.net Core Webapi,我从另一个团队获得了一个代码,这是一个.net core 2.2 web api,带有一个控制器:CustomerDemandController,我必须创建另一个(ManagerDemandController),其中包含几乎相同的方法。在这两个控制器中,我都有一个“Get by Id”方法。看起来是这样的: [ApiVersion(Constants.LatestVersion)] [Route("api/{version:apiVersion}/[controller]/")] [Cont

我从另一个团队获得了一个代码,这是一个.net core 2.2 web api,带有一个控制器:
CustomerDemandController
,我必须创建另一个(
ManagerDemandController
),其中包含几乎相同的方法。在这两个控制器中,我都有一个“Get by Id”方法。看起来是这样的:

[ApiVersion(Constants.LatestVersion)]
[Route("api/{version:apiVersion}/[controller]/")]
[ControllerName("customerdemands")]
[Produces("application/json")]
[EnableCors("SiteCorsPolicy")]
public class CustomerDemandController : ControllerBase
{
    private const string GetByIdOperation = "GetById";

    [Get("{id}", Name = GetByIdOperation)]
        public async Task<ActionResult<CustomerDemandResponse>> GetAsync([FromRoute] string id)
            => await this.GetAsync(() => Service.GetByIdAsync(id),
                                   ConversionHelper.Convert);

    ...
[ApiVersion(Constants.LatestVersion)]
[路由(“api/{version:apiVersion}/[controller]/”)
[控制器名称(“客户需求”)]
[产生(“应用程序/json”)]
[使能公司(“网站公司政策”)]
公共类CustomerDemandController:ControllerBase
{
私有常量字符串GetByIdOperation=“GetById”;
[获取(“{id}”,Name=GetByIdOperation)]
公共异步任务GetAsync([FromRoute]字符串id)
=>等待这个.GetAsync(()=>服务.GetByIdAsync(id),
ConversionHelper.Convert);
...
(在另一个控制器中使用相同的方法,将ManagerDemandResponse作为响应)。 现在,我已经添加了新的控制器,我想测试旧的控制器是否仍然有效,并且由于两个控制器中的路由名称“GetById”相同,情况不再如此

System.InvalidOperationException:属性路由信息出现以下错误:

错误1:具有相同名称“GetById”的属性路由必须具有 同一模板:操作: 'DemandManagement.Api.Controller.CustomerDemandController.GetAsync (DemandManagement.Api)“”-模板: 'api/{version:apiVersion}/customerdemands/{id}'操作: 'DemandManagement.Api.Controllers.ManagerDemandController.GetAsync (DemandManagement.Api)“”-模板: 'api/{version:apiVersion}/managerdemands/{id}'


由于控制器名称不同,我如何拥有相同的模板?

这里的问题是路由名称,而不一定是模板。更改路由名称。路由名称应唯一,以避免路由冲突

//...
public class CustomerDemandController : ControllerBase
{
    private const string GetByIdOperation = "GetCustomerDemandById"; //<-- Unique

    [Get("{id}", Name = GetByIdOperation)]
    public async Task<ActionResult<CustomerDemandResponse>> GetAsync([FromRoute] string id)
            => await this.GetAsync(() => Service.GetByIdAsync(id),
                                   ConversionHelper.Convert);

    //...
/。。。
公共类CustomerDemandController:ControllerBase
{

private const string GetByIdOperation=“GetCustomerDemandById”;//问题是路由名称而不是模板。更改路由名称。这需要是唯一的,以避免路由冲突您是说我应该有“GetCustomerDemandById”和“GetManagerDemandById”吗,例如?是的,这更容易理解,目的也更明确。我提供了一个指向文档的链接,对其进行了详细解释。