简体   繁体   English

Web API 2 / MVC 5:属性路由将参数作为查询字符串传递,以在同一控制器上定位不同的操作

[英]Web API 2 / MVC 5 : Attribute Routing passing parameters as querystring to target different actions on same controller

I've been playing with the new Web API 2 (which looks very promising btw) but I'm having a bit of a headache to get some routes working. 我一直在玩新的Web API 2(看起来非常有前途)但是我有点头疼让一些路线工作。 All works fine when I have GetAllUsers / GetUser(int id), but then when I add GetUserByName(string name) and/or GetUserByUsername(string username) things start to be creepy. 当我有GetAllUsers / GetUser(int id)时,一切正常,但是当我添加GetUserByName(字符串名称)和/或GetUserByUsername(字符串用户名)时,事情开始令人毛骨悚然。 I know that the int will be the first one and that I can re-order the routes but let's imagine the following scenario: 我知道int将是第一个,我可以重新排序路线,但让我们想象下面的场景:

A user can have a valid username=1234 or name=1234 (I know it's unlikely but we need to prevent any possible situation) and we might have a valid 1234 ID in the database and all the routes will be mixed up. 用户可以拥有有效的username=1234或者name=1234 (我知道它不太可能,但我们需要防止任何可能的情况),我们可能在数据库中有一个有效的1234 ID,并且所有路由都将被混淆。

Maybe this is something that we will need to work with on the new WebAPI 2 so I thought I could come with an "workaround" passing filters as querystrings to target different action in the same controller, such as api/users/?username=1234 (GetUserByUsername) or api/users/?name=1234 (GetUserByName) 也许这是我们需要在新的WebAPI 2上使用的东西,所以我想我可以带来一个“解决方法”,将过滤器作为查询字符串传递给同一个控制器中的不同操作,例如api/users/?username=1234 (GetUserByUsername)或api/users/?name=1234 (GetUserByName)

But I cannot make querystrings to come through ... actually any querystring option above is getting caught by the GetAllUsers. 但我不能让查询字符串通过......实际上上面的任何查询字符串选项都被GetAllUsers捕获。

Does anyone have any suggestion/fix for that scenario? 有没有人对这种情况有任何建议/解决方案?

Thanks a lot 非常感谢

You need to define the method access name like 您需要定义方法访问名称,如

[HttpGet("User")]
public async Task<UserViewModel> GetByName(string name)
[HttpGet("User")]
public async Task<UserViewModel> GetByUserName(string name)

//You can access like 
//- api/Users/User?name=someneme
//- api/Users/User?username=someneme

OR 要么

[HttpGet("User")]
public async Task<UserViewModel> GetByAnyName(string name="", string username="")
//- api/Users/User?name=someneme
//- api/Users/User?username=someneme
//- api/Users/User?username=someneme&name=someone

UPDATED Above both will work nicely with other configurations of route prefix. 更新以上两者将与其他路由前缀配置很好地协作。

OR 要么

[HttpGet("")]
public async Task<UserViewModel> GetAll()
[HttpGet("")]
public async Task<UserViewModel> Get(int id)
[HttpGet("")]
public async Task<UserViewModel> GetByName(string name)
[HttpGet("")]
public async Task<UserViewModel> GetByUserName(string name)

//You can access like 
//- api/Users/
//- api/Users/?id=123
//- api/Users/?name=someneme
//- api/Users/?username=someneme

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM