在MVC 6 Web Api中访问查询字符串
本文关键字:访问 查询 字符串 Api MVC Web | 更新日期: 2023-09-27 18:14:16
我试图在MVC 6 (asp.net 5) Web Api中添加Get()函数,以传递配置选项作为查询字符串。下面是我已经拥有的两个函数:
[HttpGet]
public IEnumerable<Project> GetAll()
{
//This is called by http://localhost:53700/api/Project
}
[HttpGet("{id}")]
public Project Get(int id)
{
//This is called by http://localhost:53700/api/Project/4
}
[HttpGet()]
public dynamic Get([FromQuery] string withUser)
{
//This doesn't work with http://localhost:53700/api/Project?withUser=true
//Call routes to first function 'public IEnumerable<Project> GetAll()
}
我尝试了几种不同的方法来配置路由,但是MVC 6的文档很少。我真正需要的是一种方法来传递一些配置选项的项目列表排序,自定义过滤等
在单个控制器中不能有两个具有相同template
的[HttpGet]
。我正在使用asp.net5-beta7,在我的情况下,它甚至抛出以下异常:
Microsoft.AspNet.Mvc.AmbiguousActionException多个动作匹配。以下操作匹配路由数据并满足所有约束:
这样做的原因是[From*]
属性意味着绑定,而不是路由。
下面的代码应该可以为您工作:
[HttpGet]
public dynamic Get([FromQuery] string withUser)
{
if (string.IsNullOrEmpty(withUser))
{
return new string[] { "project1", "project2" };
}
else
{
return "hello " + withUser;
}
}
还可以考虑使用Microsoft.AspNet.Routing.IRouteBuilder.MapRoute()
代替属性路由。
通过使用RESTful路由约定(由ASP强制执行)访问查询字符串是非常可行的。. NET 5/MVC 6(默认)或定义自定义路由,如本答案所述。
下面是使用基于属性的自定义路由的快速示例:[HttpGet("GetLatestItems/{num}")]
public IEnumerable<string> GetLatestItems(int num)
{
return new string[] { "test", "test2" };
}
有关自定义路由的更多信息,请阅读我博客上的以下文章