xamarin 将数组作为Http客户端多部分/表单数据发送到API

cgyqldqp  于 2022-12-07  发布在  其他
关注(0)|答案(2)|浏览(108)

我有一个端点请求我发送一个数组作为我的主体数据的一部分,下面是我使用多部分表单数据的代码。如何将数组发送到我的端点。

var file = _mediaFile.Path;

if (string.IsNullOrEmpty(file) == false)
{
    var upfilebytes = System.IO.File.ReadAllBytes(file);

    MultipartFormDataContent content = new MultipartFormDataContent();
    ByteArrayContent baContent = new ByteArrayContent(upfilebytes);
    var name = System.IO.Path.GetFileName(file);

    baContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/" + System.IO.Path.GetExtension(name).Remove(0, 1));
    baContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data")
                {
                    Name = "Image",
                    FileName = name,
                };

    var categorynew = new List<string>();
    categorynew.Add(((Categorypicker.SelectedItem as CategoriesModel).category));

    var categoryArray = categorynew.ToArray();

    content.Add(baContent, "Image", name);
    content.Add(new StringContent(DealerAddr.Text), "DealersAddress");
    content.Add(new StringContent(itemName.Text), "ItemName");
    content.Add(new StringContent(itemDescription.Text), "ItemDescription");
    content.Add(new StringContent(itemPrice.Text), "PreferredPrice");
    content.Add(new StringContent(DealerPhone.Text), "DealerPhone");
    content.Add(new StringContent(DealerCity.Text), "City");
    content.Add(new StringContent(StoreUrl.Text), "SellerWeblink");
    content.Add(new StringContent (categorynew,"Category_Name");
    content.Add(new StringContent((Categorypicker.SelectedItem as CategoriesModel).category), "Category_Name");

    var response = await client.PostAsync(CreateItem, content);

    if (response.IsSuccessStatusCode) 
    {
    }
}
xesrikrc

xesrikrc1#

好的,我后来解决了这个问题,在将它添加到我的内容之前,我的数组转换回json。

var categorynew = new List<string>();
categorynew.Add(((Categorypicker.SelectedItem as CategoriesModel).category));

var categoryArray = categorynew.ToArray();
var jsoncategoryArray = JsonConvert.SerializeObject(categoryArray);

content.Add(baContent, "Image", name);
content.Add(new StringContent(DealerAddr.Text), "DealersAddress");
content.Add(new StringContent(itemName.Text), "ItemName");
content.Add(new StringContent(itemDescription.Text), "ItemDescription");
content.Add(new StringContent(itemPrice.Text), "PreferredPrice");
content.Add(new StringContent(DealerPhone.Text), "DealerPhone");
content.Add(new StringContent(DealerCity.Text), "City");
content.Add(new StringContent(StoreUrl.Text), "SellerWeblink");
content.Add(new StringContent(jsoncategoryArray),"category");
km0tfn4u

km0tfn4u2#

对我来说,有一个更好的解决方案,它不需要任何数据内容操作,假设我们正在等待一个名为“Categories”的参数中的数组:

foreach(var cat in categories)
                mfd.Add(new StringContent(arg, Encoding.UTF8), "Categories[]");

相关问题