我正在尝试使用Web Client从我的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);
}
}
答案 0 :(得分:0)
ASP.NET WebApi会自动将具有相同名称的参数转换为数组,如果这是您定义服务操作的方式。因此,如果您的URL是// ip:port / api / Items /?Color = 1&amp; Color = 2,Colour
数组将等于服务器端的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());