3

我是 REST 服务的新手,一直在研究 ASP.Net Web API 的示例。我想做的是扩展这个 Get 方法:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class ProductsController : ApiController
{
    public IEnumerable<Product> GetAllProducts()
    {
        return new List<Product> 
        {
            new Product() { Id = 1, Name = "Gizmo 1", Price = 1.99M },
            new Product() { Id = 2, Name = "Gizmo 2", Price = 2.99M },
            new Product() { Id = 3, Name = "Gizmo 3", Price = 3.99M }
        };
    } ...

对于我发送产品列表并返回所有价格的东西,在概念上它看起来像这样:

    public IEnumerable<Product> GetProducts(string[] ProductNames)
    {
        var pList = new List<Product>; 
        foreach (var s in ProductNames)
        {
            //Lookup price
            var LookedupPrice = //get value from a data source
            pList.Add(new Product() { Id = x, Name = s, Price = LookedUpPrice });

        }
        return pList;
    }

有什么想法,REST 调用会是什么样子?我在想我需要传入一个 JSON 对象,但真的不确定。

4

1 回答 1

4

使用查询字符串值,您可以将多个值与单个字段相关联

public class ValuesController : ApiController
{
    protected static IList<Product> productList;
    static ValuesController()
    {
        productList = new List<Product>()
        {
            new Product() { Id = 1, Name = "Gizmo 1", Price = 1.99M },
            new Product() { Id = 2, Name = "Gizmo 2", Price = 2.99M },
            new Product() { Id = 3, Name = "Gizmo 3", Price = 3.99M }
        };
    }                
    public IEnumerable<Product> Get(IEnumerable<int> idList)
    {
        return productList;
    }
}

使用默认路由,您现在可以向以下端点发出 GET 请求

/api/values/FilterList?idList=1&idList=2

于 2012-04-14T04:12:29.517 回答