当未在 Web 中的查询字符串中传递时实例化的可选列表参数 API

Optional list param coming in as instantiated when not passed in query string in Web API

我的 Web API 方法如下所示:

[HttpGet]
public IList<Product> Get(List<int> categoryIds = null)
{
    IList<Product> prods = _productService.GetProducts(categoryIds);
    return prods;
}

为什么当我简单地调用 api/products 时没有查询字符串参数类别 ID 没有作为空值出现?相反,它的计数为 0

操作所需的对象 (List<int> categoryIds) 使用其默认构造函数 实例化,然后 模型绑定在 URL 中查找匹配项以填充它。由于模型绑定没有找到任何参数以进一步放入 List<int>,它刚刚被更新。

来自MVC Model Binding

In order for binding to happen the class must have a public default constructor and member to be bound must be public writable properties. When model binding happens the class will only be instantiated using the public default constructor, then the properties can be set.

For those types such as 'Collection' types, model binding looks for matches to parameter_name[index] or just [index].

您可以将列表包含在复杂对象中并在操作中接受该对象:

public class Request
{
    public List<int> categoryIds { get; set; }
}

然后在您的控制器操作中:

[Route("api/[controller]")]
public class ValuesController : Controller
{
    // GET api/values
    [HttpGet]
    public IEnumerable<int> Get(Request request)
    {
        return request.categoryIds;
    }
}

那么您的请求将是:

/api/values?categoryIds[0]=0&categoryIds[1]=1