我从另一个团队那里得到了一个代码,这是一个带有控制器的{。{1}}的.net核心2.2 Web api,我必须使用与...中几乎相同的方法来创建另一个(CustomerDemandController
)。它。在这两个控制器中,我都有一个“通过ID获取”方法。看起来像这样:
ManagerDemandController
(另一个控制器中以ManagerDemandResponse作为响应的相同方法)。 现在,我已经添加了新的控制器,我想测试旧的控制器是否仍然有效,并且由于两个控制器中的路由名称均为“ GetById”相同,因此不再适用。
System.InvalidOperationException:属性路由信息发生以下错误:
错误1:具有相同名称“ GetById”的属性路由必须具有 相同的模板:操作: 'DemandManagement.Api.Controllers.CustomerDemandController.GetAsync (DemandManagement.Api)'-模板: 'api / {version:apiVersion} / customerdemands / {id}'操作: 'DemandManagement.Api.Controllers.ManagerDemandController.GetAsync (DemandManagement.Api)'-模板: 'api / {version:apiVersion} / managerdemands / {id}'
由于控制器名称不同,我如何拥有相同的模板?
答案 0 :(得分:1)
这里的问题是路由名称,不一定是模板。更改路线名称。路由名称应唯一以避免路由冲突。
//...
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);
//...
路由名称可用于根据特定路由生成URL。路由名称对路由的URL匹配行为没有影响,仅用于URL生成。 路由名称在应用程序范围内必须是唯一的。
强调我的