简体   繁体   中英

c# passing multiple lists to FormUrlEncodedContent

I am performing a HTTP requests and I would like to pass multiple items to my post request.

public async Task<HttpResponseMessage> SubmitInspection(
                List<NewsModel> newitems, List<ChildrenModel> childs)
{

    //how do i add the above lists to one item to pass to the http body
    var values =  //stuck here = newitems and childs lists

    var body= new FormUrlEncodedContent(values);
    var response = await http.PostAsync(url, body);
    return response;
}

How do I add both List items(passed as parameters in the method above) to my HTTP body?

Simply declare an array and initialize the FormUrlEncodedContent with it:

   var values =  new[] { newitems, childs}
   var body= new FormUrlEncodedContent(values);

You can pass on data like this as well.

public async Task<HttpResponseMessage> SubmitInspection(List<object> newitems, List<object> childs)
    {
        //how do i add the above lists to one item to pass to the http body
        //stuck here = newitems and childs lists
        var myContent = Newtonsoft.Json.JsonConvert.SerializeObject(new { newitems, childs });
        var buffer = System.Text.Encoding.UTF8.GetBytes(myContent);
        var byteContent = new ByteArrayContent(buffer);
        byteContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

        var response = await new HttpClient().PostAsync("", byteContent);
        return response;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM