将 IEnumerable<int> 传递给 WebApi 操作



我有此控制器操作:

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

我还使用了这个问题所述的自定义模型粘合剂。我的问题与这个链接的问题不同,因为即使我遵循了建议的答案,但在使用自定义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 
}

但是,响应抛出了一个未发现的例外。

我在这里缺少什么?

编辑

我删除了自定义模型活页夹的注册,然后将操作更改为:

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

现在我得到以下例外:

httpexception(0x80004005):潜在的危险请求。从客户端检测到路径值(?)

因此,如果在URL中不允许使用?,并且在不删除验证的情况下,如何将数组传递给操作?将Get更改为Post是否有意义(为了使用请求。

如果您的控制器动作为

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

并将URL传递为:

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

它应该只能在没有自定义粘合剂的情况下工作

最新更新