在 MVC 6 Web Api 中访问查询字符串?

Accessing the query string in MVC 6 Web Api?

我正在尝试在 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 Multiple actions matched. The following actions matched route data and had all constraints satisfied:

原因是 [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 强制执行)或通过定义自定义路由,访问查询字符串是非常可行的,如 [=11 中所述=].

这是使用自定义 基于属性 路由的快速示例:

[HttpGet("GetLatestItems/{num}")]
public IEnumerable<string> GetLatestItems(int num)
{
    return new string[] { "test", "test2" };
}

有关自定义路由的详细信息,请阅读我的博客 the following article