在不使用OData约定的情况下传递查询字符串参数?

Aar*_*web 8 c# asp.net-mvc-routing asp.net-mvc-4 asp.net-web-api

有没有办法将查询字符串参数传递给ASP.NET MVC4 Web Api控制器而不使用此处概述的OData约定?

http://www.asp.net/web-api/overview/web-api-routing-and-actions/paging-and-querying

我有一些使用Dapper构建的存储库方法,它们不支持IQueryable,并且希望能够在不使用OData约定的情况下手动对它们进行分页,但每当我尝试使用传统的ASP.NET方式时,我会得到"route not found"错误.

例如,这是一条路线:

context.Routes.MapHttpRoute(
           name: "APIv1_api_pagination",
           routeTemplate: "api/v1/{controller}/{id}",
           defaults: new { area = AreaName, controller = "category", offset = 0, count = 100});
Run Code Online (Sandbox Code Playgroud)

这是匹配的签名

public class CategoryController : ApiController
{
    // GET /api/<controller>
    public HttpResponseMessage Get(int id, int offset = 0, int count = 0)
Run Code Online (Sandbox Code Playgroud)

每当我传递以下查询时:

http://localhost/api/v1/category/1?offset=10

我收到以下错误:

未在与请求匹配的控制器"类别"上找到任何操作.

有关如何在ASP.NET MVC4 Web Api中使用查询字符串的任何建议吗?

kko*_*yik 11

当您开始使用查询字符串时,您实际上使用其参数调用控制器的精确方法.我更喜欢你改变你的路由器:

context.Routes.MapHttpRoute(
       name: "APIv1_api_pagination",
       routeTemplate: "api/v1/{controller}/{action}/{id}",
       defaults: new { area = AreaName, controller = "category", offset = 0, count = 100});
Run Code Online (Sandbox Code Playgroud)

然后将您的方法更改为

public HttpResponseMessage Items(int id, int offset = 0, int count = 0);
Run Code Online (Sandbox Code Playgroud)

从现在开始,每当你查询时

http://localhost/api/v1/category/Items?id=1&offset=10&count=0
Run Code Online (Sandbox Code Playgroud)

它会运行.

写这篇文章时,我想到了另一种方法.我不知道它是否有效但是尝试改变你的路由器

context.Routes.MapHttpRoute(
       name: "APIv1_api_pagination",
       routeTemplate: "api/v1/{controller}/{id}/{offset}/{count}",
       defaults: new { area = AreaName, controller = "category", offset = RouteParameter.Optional, count = RouteParameter.Optional});
Run Code Online (Sandbox Code Playgroud)