1

我正在尝试使用 Web 客户端从我的 WP8 应用程序传递一个整数数组作为 GET Web API 的标准。我已经尝试过下载和上传字符串,但无法将条件传递给 API

以下是我当前的代码

Web API 控制器方法

public IQueryable<Items> GetItemByColour([FromUri] int[] Colour)
{
var query = from a in db.Items
        where Colour.Contains(a.ItemsColour)
        select a;

return query;}

WP8 应用程序

void btnGetData_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            WebClient webClient = new WebClient();
            int[] arr = new int[3];
            arr[0] = 1;
            arr[1] = 2;
            arr[2] = 3;

            Uri uri = new Uri("http://ip:Port/api/Items/?Colour="+arr);
            webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
            webClient.DownloadStringAsync(uri);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        try
        {
            List<Items> items = JsonConvert.DeserializeObject<List<Items>>(e.Result);
            foreach (Item em in items)
            {
                int phoneID = em.ItemID;
                string phoneName = em.ItemName;
                lstPhones.Items.Add(phoneId + " " + phoneName);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
4

1 回答 1

0

如果这是您定义服务操作的方式,ASP.NET WebApi 将自动将具有相同名称的参数转换为数组。因此,如果您的 URL 是 //ip:port/api/Items/?Colour=1&Colour=2Colour数组将等于int[2] { 1, 2 }服务器端。

如果您这样做,它应该可以正常工作:

 int[] arr = new int[3] { 1, 2, 3 };
 System.Text.StringBuilder colourParams = new System.Text.StringBuilder();

 for (int i = 0; i < arr.Length; i++)
 {
     colourParams.Append("Colour=").Append(arr[i]);
     if (i != arr.Length - 1)
     {
         colourParams.Append("&");
     }
 }

 Uri uri = new Uri("http://ip:port/api/Items/?" + colourParams.ToString());
于 2013-07-28T19:54:26.043 回答