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. 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. 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:
我一直在使用新的Web API 2(看起来非常有前途)但我有点头疼让一些路由工作。当我有GetAllUsers / GetUser(int id)时,一切正常,但是当我添加GetUserByName(字符串名称)和/或GetUserByUsername(字符串用户名)时,事情开始令人毛骨悚然。我知道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.
用户可以拥有有效的用户名= 1234或者名称= 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
非常感谢
13
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
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2013/10/15/531fd19cce8ca94647d4a2eb38d15cd7.html。