4

I am trying to pass in a list of integers to a C# controller action. I have the following code:

    HttpRequestMessage request;
    String myUrl = 'http://path/to/getData';
    List<int> data = new List<int>() { 4, 6, 1 };

    request = new HttpRequestMessage(HttpMethod.post, myUrl);
    request.Content = new StringContent(JsonConvert.SerializeObject(data, Formatting.Indented));

    HttpResponseMessage response = httpClient.SendAsync(request).Result;
    String responseString = response.Content.ReadAsStringAsync().Result;
    var data = (new JavaScriptSerializer()).Deserialize<Dictionary<string, object>>(responseString);

The controller action:

    [HttpPost]
    [ActionName("getData")]
    public Response getData(List<int> myInts) {

        // ...

    }

However the resulting responseString is:

 {"Message":"An error has occurred.","ExceptionMessage":"No MediaTypeFormatter is available to read an object of type 'List`1' from content with media type 'text/plain'.","ExceptionType":"System.InvalidOperationException}
user2181948
  • 1,646
  • 3
  • 33
  • 60
  • If one of the answers has helped you, please upvote and mark it as the answer. If your question is still unanswered, please let us know. If you found a different answer to your question, please post it as an answer. Thanks! :) – pcdev Dec 20 '17 at 05:19

2 Answers2

1

Similar to this question - you are not sending a List<int>, you are sending a serialized list of integers (in this case, a JSON serialized string). So you need to accept a string and deserialize at the other end, as well as handling any non-integer values that might be encountered. Something like this:

[HttpPost]
[ActionName("getData")]
public Response getData(string myInts) {

    var myIntsList = JsonConvert.DeserializeObject<List<int>>(myInts);
    // Don't forget error handling!

}

EDIT 2:

The other alternative is to add multiple query parameters like so:

http://path/to/getData?myInts=4&myInts=6&myInts=1

This should work with the code that you have already. ASP.NET can interpret multiple query parameters as a List<T>).

Sorry, you may need to add the [FromUri] attribute for the solution:

[HttpPost]
[ActionName("getData")]
public Response getData([FromUri]List<int> myInts) {

    // ...

}
pcdev
  • 2,852
  • 2
  • 23
  • 39
0

It is easy if you utilize Microsoft.AspNet.WebApi.Client package in client application

Action method

// POST api/values
        public void Post(List<int> value)
        {
        }

client application

class Program
    {
        static void Main(string[] args)
        {
            using (var client = new HttpClient())
            {
                var result = client.PostAsJsonAsync("http://localhost:24932/api/values",
                    new List<int>() {123, 123, 123}).Result;

                Console.ReadLine();
            }
        }
    }
Dan Nguyen
  • 1,308
  • 6
  • 17