C# 当存在多条路由时,使用查询字符串的路由属性路由

C# 当存在多条路由时,使用查询字符串的路由属性路由,c#,asp.net-web-api,asp.net-web-api-routing,C#,Asp.net Web Api,Asp.net Web Api Routing,我有这个: [HttpGet] [Route("Cats")] public IHttpActionResult GetByCatId(int catId) [HttpGet] [Route("Cats")] public IHttpActionResult GetByName(string name) 通过提供查询字符串来调用它们,例如Cats?catId=5 然而,MVCWebAPI会说,不能有多条相同的路由(两条路由都是“猫”) 我如何才能使其工作,使MVC Web API将它们识别为

我有这个:

[HttpGet]
[Route("Cats")]
public IHttpActionResult GetByCatId(int catId)

[HttpGet]
[Route("Cats")]
public IHttpActionResult GetByName(string name)
通过提供查询字符串来调用它们,例如
Cats?catId=5

然而,MVCWebAPI会说,不能有多条相同的路由(两条路由都是“猫”)


我如何才能使其工作,使MVC Web API将它们识别为单独的路由?我是否可以在路由属性中输入一些内容?它说,
是一个无效的字符,无法输入路由。

尝试对属性路由应用约束

[HttpGet]
[Route("Cats/{catId:int}")]
public IHttpActionResult GetByCatId(int catId)

[HttpGet]
[Route("Cats/{name}")]
public IHttpActionResult GetByName(string name)

您可以将有问题的两个操作合并为一个

[HttpGet]
[Route("Cats")]
public IHttpActionResult GetCats(int? catId = null, string name = null) {

    if(catId.HasValue) return GetByCatId(catId.Value);

    if(!string.IsNullOrEmpty(name)) return GetByName(name);

    return GetAllCats();
}

private IHttpActionResult GetAllCats() { ... }

private IHttpActionResult GetByCatId(int catId) { ... }    

private IHttpActionResult GetByName(string name) { ... }
或者,为了获得更大的灵活性,请尝试使用管线约束

参考

路线约束

管线约束允许您限制管线中参数的使用方式 模板匹配。通用语法为“{parameter:constraint}”。 例如:

[Route("users/{id:int}"]
public User GetUserById(int id) { ... }

[Route("users/{name}"]
public User GetUserByName(string name) { ... }
此处,仅当路线的“id”段 URI是一个整数。否则,将选择第二条路由


默认情况下它是字符串。无需放置它,只需放置
{name}
此方法意味着
users/5
可以工作,但不能
/users?name=5
,这正是我需要的。在这种情况下,您必须将这两个方法合并为一个,并根据填充的参数执行操作。否则,您需要进一步区分这两个操作,以避免路由冲突mapping@NibblyPig,核对更新答案并查看是否适用于您尝试过此方法后,它不会区分名称,因此如果您有两条路径,一条路径为
string catId
,另一条路径为
string catName
,如果您转到
theUrl?catId=CAT75
或“theUrl?catName”,则会发现一个错误
发现与请求匹配的多个操作=Jeff.如果我使用一条包含两个参数的路线,它就不能很好地处理swagger/Swashback或其他类似于日志记录的东西:(