gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:18:52 24 4
gpt4 key购买 nike

有没有办法在不使用此处概述的 OData 约定的情况下将查询字符串参数传递给 ASP.NET MVC4 Web Api Controller ?

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

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

例如,这是一条路线:

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

这是匹配的签名

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

每当我通过以下查询时:

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

我收到以下错误:

No action was found on the controller 'Category' that matches the request.

关于如何在 ASP.NET MVC4 Web Api 中合理地使用查询字符串有什么建议吗?

最佳答案

当您开始使用 querystring 时,您实际上调用了带有参数的 Controller 的确切方法。我希望您像这样更改路由器:

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

然后把你的方法改成

public HttpResponseMessage Items(int id, int offset = 0, int count = 0);

从现在开始,只要你查询喜欢

http://localhost/api/v1/category/Items?id=1&offset=10&count=0

它将运行。

在写这篇文章时,我想到了另一种方法。我不知道它是否有效,但请尝试像这样更改您的路由器

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});

关于c# - 在不使用 OData 约定的情况下传递查询字符串参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10891935/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com