网页API 2 / MVC 5:属性路由传递参数的查询字符串的目标来同一个控制器不同的操作 [英] Web API 2 / MVC 5 : Attribute Routing passing parameters as querystring to target different actions on same controller
问题描述
我一直在玩新的Web API 2(这看起来非常有前途的BTW),但我有一点头疼得到一些路线的工作。
当我有GetAllUsers /的getUser(INT ID),但后来当我添加GetUserByName(字符串名称)和/或GetUserByUsername(字符串的用户名),做起事情来会令人毛骨悚然的一切工作正常。我知道,INT将是第一个,我可以重新排序的路线,但让我们想象一下以下情形:
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:
一个用户可以拥有一个有效的用户名= 1234
或名称= 1234
(我知道这是不可能的,但我们需要以prevent任何可能发生的情况),我们可能会在数据库中的有效ID 1234,所有的路线会被混淆。
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.
也许这是后话,我们需要在新的WebAPI 2,所以我想我能拿出一个解决办法通过过滤器作为查询字符串的目标在同一个控制器不同的动作,如 API /用户/?用户名= 1234
(GetUserByUsername)或 API /用户/?NAME = 1234
(GetUserByName)
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)
但我不能让查询字符串来通过...其实任何查询字符串选项上面得到的GetAllUsers抓住了。
But I cannot make querystrings to come through ... actually any querystring option above is getting caught by the GetAllUsers.
有没有人有这种情况的任何建议/修复?
Does anyone have any suggestion/fix for that scenario?
非常感谢
推荐答案
您需要定义像
[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
或
[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
更新时间:
以上两者都将有航线preFIX的其他配置很好地工作。
UPDATED Above both will work nicely with other configurations of route prefix.
或
[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
这篇关于网页API 2 / MVC 5:属性路由传递参数的查询字符串的目标来同一个控制器不同的操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!