当存在多个路由时,使用查询字符串进行路由属性路由 [英] Route attribute routing with query strings when there are multiple routes

查看:91
本文介绍了当存在多个路由时,使用查询字符串进行路由属性路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个:

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

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

通过提供查询字符串(例如Cats?catId=5

They are called by providing the query string eg Cats?catId=5

但是MVC Web API会说您不能有多个相同的路由(两个路由都是猫".

However MVC Web API will say you can't have multiple routes that are the same (both routes are "Cats".

如何使它起作用,以便MVC Web API将其识别为单独的路由?我可以在Route属性中添加一些内容吗?它说?是放置在路由中的无效字符.

How can I get this to work so MVC Web API will recognize them as separate routes? Is there something I can put into the Route property? It says that ? is an invalid character to put into a route.

推荐答案

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

You can merge the two actions in question into one

[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) { ... }

或者为了获得更大的灵活性,请尝试路由约束

Or for more flexibility try route constraints

引用 ASP.NET Web API 2中的属性路由:路由约束

路线约束

路线约束可让您限制路线中的参数 模板是匹配的.通用语法为"{parameter:constraint}". 例如:

Route constraints let you restrict how the parameters in the route template are matched. The general syntax is "{parameter:constraint}". For example:

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

[Route("users/{name}"]
public User GetUserByName(string name) { ... }

在这里,只有在 URI是一个整数.否则,将选择第二条路线.

Here, the first route will only be selected if the "id" segment of the URI is an integer. Otherwise, the second route will be chosen.

这篇关于当存在多个路由时,使用查询字符串进行路由属性路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆