【问题标题】:How to send string array as a query parameter to WebAPI from C# http client如何从 C# http 客户端将字符串数组作为查询参数发送到 WebAPI
【发布时间】:2017-11-27 11:17:38
【问题描述】:

我们应用程序的后端公开了接受 IEnumerable 的 web api。以下是示例定义:

[HttpGet]
public HttpResponseMessage Get(int? id = null, [FromUri]IEnumerable<string> category = null)

我正在手动创建带有查询参数的 URL,如下所示:

category=category1&category=category2

..并将其附加到实际 URL 以获得结果。

有没有更好的方法将类别列表添加为查询参数而不是手动创建 url?将字符串数组传递到 URI 中的端点的最佳方法是什么?

【问题讨论】:

  • 试试/foo/id=123?category=category1&amp;category=category2(注意?123之后)
  • 端点中的所有参数都是可选的。我错过了添加。请查看编辑。
  • one way。或者您可以发帖,因为您可能会达到 2048 个字符的限制。或者你可以有一个带分隔符的参数。
  • @lloyd:按照您的建议,我将不得不要求 backedn 团队更改端点,因为它必须接受来自标头的参数,这目前是不可能的。

标签: c# arrays asp.net-web-api httpclient


【解决方案1】:

就这样试试吧;

/foo/Get?id=123&category=category1,category2

您可以使用comma(,) 分隔数组元素。

【讨论】:

  • 响应是错误请求
【解决方案2】:

我假设您已将 WebAPI 设置的路由设置为默认设置:

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }

您需要在id 上将您的方法签名更新为包含 [FromUri]

public IEnumerable<string> Get([FromUri]int? id = null, [FromUri]IEnumerable<string> category = null) {...}

这将允许id来自 Uri 而不是路由数据。

因此意味着如果您向以下对象发出 get 请求:

GET /api/foo?id=123&category=category1&category=category2

这应该给你的预期值

id = 123

category = ["category1", "category2"]

您还可以执行以下请求:

GET /api/foo?category=category1&category=category2

并且会给你预期的值

id = null

category = ["category1", "category2"]

【讨论】:

  • enpoint 的所有参数都是可选的。请参阅更新的问题。不幸的是,您建议的方式不起作用。
  • @Ajinkya 根据变更问题修正了答案 :-)
  • 感谢您的编辑。正如我在请求/foo/id=&amp;category=category1&amp;category=category2 的问题中提到的那样,响应是错误的请求。
  • 在您的示例中,它试图将 id=&amp;category=category1&amp;category=category2 转换为 int 这是不可能的 - 400 Bad request
  • 参数id是可以为空的int
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-18
  • 2019-04-09
  • 1970-01-01
  • 2020-10-10
  • 1970-01-01
  • 1970-01-01
  • 2016-06-30
相关资源
最近更新 更多