【问题标题】:post array as Httpclient multipart/form-data to api将数组作为 Httpclient multipart/form-data 发布到 api
【发布时间】:2019-11-28 21:46:20
【问题描述】:

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

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) 
    {
    }
}

【问题讨论】:

  • 也许this 会有所帮助。

标签: c# forms xamarin mobile


【解决方案1】:

好的,我后来通过在将数组添加到我的内容之前将它转换回 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");

【讨论】:

  • 很高兴听到这个消息。谢谢分享答案,以后有时间记得标记一下:)
猜你喜欢
  • 1970-01-01
  • 2019-05-03
  • 2018-12-31
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多