带有字符串参数的HttpClient GET方法

时间:2019-01-14 11:00:52

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

我正在制作一个将托管数据库并通过Web API与网站和wpf应用程序通信的应用程序。因此,问题是这样的:如何使用字符串参数发出GET请求?我已经做过类似的事情,但是使用了整数参数。几乎相同的代码不适用于字符串参数。为什么?

适用于int参数的代码: 控制器方法:

[HttpGet]
    [ActionName("GetResItems")]
    public IHttpActionResult GetResItems(int id)
    {
        using (var db = new FoodOrderingContext())
        {
            List<ItemsInRestaurant> list = db.ItemsInRestaurants.Where(x => x.ItemId == id).ToList();
            List<ItemsInRestaurantVM> toSend = new List<ItemsInRestaurantVM>();

            foreach (var item in list)
            {
                toSend.Add(new ItemsInRestaurantVM(item));
            }

            if (toSend.Count == 0)
            {
                return NotFound();
            }

            return Ok(toSend);
        }
    }

客户端WPF端的代码:

public List<ItemsInRestaurantVM> GetResItems(int id)
    {
        List<ItemsInRestaurantVM> list = null;

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:52407/");
            var responseTask = client.GetAsync("api/item/getresitems/" + id);
            responseTask.Wait();

            var result = responseTask.Result;
            if (result.IsSuccessStatusCode)
            {
                var readingTask = result.Content.ReadAsAsync<List<ItemsInRestaurantVM>>();
                readingTask.Wait();

                list = readingTask.Result;
            }
        }

        return list;
    }

现在,无效的代码: 服务器端:

[HttpGet]
    [ActionName("GetTop10Items")]
    public IHttpActionResult GetTop10Items(string type)
    {
        using (var db = new FoodOrderingContext())
        {
            List<Top10ItemsVM> list = new List<Top10ItemsVM>();

            foreach (var item in db.Items.ToList())
            {
                if (item.Type.Equals(type))
                {
                    Top10ItemsVM toAdd = new Top10ItemsVM();
                    toAdd.Name = item.Name;
                    toAdd.Price = item.Price.ToString() + " $";
                    toAdd.Ammount = db.OrderItems.Where(x => x.ItemId == item.ItemId).Select(x => x.Ammount).Sum().ToString();
                    toAdd.Total = (db.OrderItems.Where(x => x.ItemId == item.ItemId).Select(x => x.Ammount).Sum() * item.Price).ToString() + " $";
                    list.Add(toAdd);
                }
            }

            if (list.Count > 0)
            {
                return Ok(list);
            }
            else
            {
                return NotFound();
            }
        }

客户端:

public List<Top10ItemsVM> GetTop10Items(string type)
    {
        List<Top10ItemsVM> list = null;

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:52407/");
            var responseTask = client.GetAsync("api/item/GetTop10Items/" + type);
            responseTask.Wait();
            var result = responseTask.Result;
            if (result.IsSuccessStatusCode)
            {
                var readTask = result.Content.ReadAsAsync<List<Top10ItemsVM>>();
                readTask.Wait();
                list = readTask.Result.OrderByDescending(x => x.Ammount).Take(10).ToList();
            }

            return list;
        }
    }

第一部分的工作原理应该是这样。第二个甚至不调用服务器方法。您可以清楚地看到它几乎是相同的代码。我在这里想念什么?

1 个答案:

答案 0 :(得分:4)

路由参数通过?param=value传输。您的第一种情况仅能起作用,因为asp.net模板添加了一个默认的路由映射,如下所示:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

其中定义了每个定义了参数id的Action方法都自动映射到:myurl/action/<id>

要使第二种情况起作用,您必须调用以下操作:

  

api / item / GetTop10Items?type = something

在其中明确定义路由参数type及其值。