Jesus is Lord
Jesus is Lord

Reputation: 15399

How do I POST an array to a web api controller from an HttpClient?

Inside a web api controller I have the following method:

[HttpPost]
public ProcessResultDto Process(int[] IDs)
{
}

I cannot change that signature or dll or anything.

I have to make an executable that calls that method.

Here's roughly what I have so far:

int[] ids = //...
using (var client = new HttpClient())
{
    var content = // I don't know what goes here.
    var result = cli.PostAsync("/api/Processor/Process", content).Result;
    string resultContent = result.Content.ReadAsStringAsync().Result;
    // Substring(6) because of leading )]}',\n
    var summary = JsonConvert.DeserializeObject<ProcessResultDto>(resultContent.Substring(6));
    return summary;
}

What do I set content to so that I can pass an array of int's to my web api controller

Upvotes: 1

Views: 2607

Answers (2)

pnewhook
pnewhook

Reputation: 4068

I use ServiceStack's JSON serializer/deserializer as they're the current .Net performance champ. From the ServiceStack docs

Any List, Queue, Stack, Array, Collection, Enumerables including custom enumerable types are stored in exactly the same way as a JavaScript array literal

Therefore

int[] ids = [1,2,3,4];
var content = TypeSerializer.SerializeToString(new {IDs=ids});

Upvotes: 1

Adam Modlin
Adam Modlin

Reputation: 3024

You could do the following:

int[] ids = new[] {1,2,3,4};
var content = JsonConvert.SerializeObject(new {
   IDs = ids
});

This will create an anonymous object with a property of IDs and convert it to json. The json will look like:

{
    IDs: [1,2,3,4]
}

The web API method will then bind that to your model.

Upvotes: 1

Related Questions