【问题标题】:Passing IEnumerable<int> to a WebApi action将 IEnumerable<int> 传递给 WebApi 操作
【发布时间】:2015-05-13 19:39:00
【问题描述】:

我有这个控制器动作:

[ActionName("GetMany")] [HttpGet]
public IHttpActionResult GetMany([FromUri] IEnumerable<int> ids)
{
    //Do something...
}

我还在使用this SO question 中描述的自定义模型绑定器。我的问题与这个链接的问题不同,因为即使我遵循了那里建议的答案,但在使用自定义 ModelBinder 时它仍然无法正常工作,因为它会引发下面提到的异常。

我已配置此路由:

config.Routes.MapHttpRoute(
    name: "ApiByAction",
    routeTemplate: "Api/{controller}/{action}",
    defaults: new { action = "Get" },
    constraints: null
);

在客户端,我会这样做:

public IEnumerable<MyEntity> LoadMany(IEnumerable<int> ids)
{
    var url = "Api/MyEntity/GetMany?ids={0}";
    var s = HttpUtility.UrlEncode(string.Format(url, string.Join(",", ids)));

    response = client.GetAsync(HttpUtility.UrlEncode(s)).Result;

    return null; //for now 
}

但是,响应会引发 Not Found 异常。

我在这里错过了什么?

编辑

我删除了自定义模型绑定器的注册,并将操作更改为:

[ActionName("GetMany")] [HttpGet]
public IHttpActionResult GetMany([ModelBinder(typeof(ArrayModelBinder))] IEnumerable<int> ids)
{
    //Do something...
}

现在我得到以下异常:

HttpException (0x80004005):从客户端检测到潜在危险的 Request.Path 值 (?)

因此,如果 URL 中不允许使用 ?,并且不删除验证,那么如何将数组传递给操作?将Get 更改为Post 是否有意义(以便使用request.body)?

【问题讨论】:

  • 你试过完整的网址而不是"Api/MyEntity/GetMany?ids={0}"吗? ("http:/www.example.com/Api/MyEntity/GetMany?ids={0}")

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


【解决方案1】:

如果你有控制器动作

public IHttpActionResult GetMany([FromUri] int[] ids)

并将 URL 传递为:

?ids=1&ids=2&ids=3...

它应该可以在没有自定义活页夹的情况下工作

【讨论】:

  • 我希望将 URL 传递为 ?ids=1,2,3
猜你喜欢
  • 2018-05-01
  • 2012-12-18
  • 2020-06-16
  • 2019-06-07
  • 2014-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多