【问题标题】:How to use ASP.Net Web API to send a list of keys and return a list of key/values?如何使用 ASP.Net Web API 发送键列表并返回键/值列表?
【发布时间】:2012-04-12 22:28:30
【问题描述】:

我是 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 对象,但真的不确定。

【问题讨论】:

    标签: asp.net rest asp.net-web-api


    【解决方案1】:

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

    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

    【讨论】:

    • 谢谢,我明白你在做什么了。我会试一试并发布我的结果。感谢您抽出宝贵时间来回答。
    • 请注意,在 WebApi RC 中,您需要在方法签名中的 idList 参数的 from 中包含 [FromUri] 属性。详情见这里:stackoverflow.com/questions/10934077
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-07
    • 1970-01-01
    • 2020-04-05
    • 1970-01-01
    • 2023-02-10
    • 2020-12-03
    相关资源
    最近更新 更多