Search code examples
dotnet-httpclientasp.net-apicontrollercustom-data-type

Sending List of custom data type with HttpClient


I'm trying to send a list made of a custom data type to a function inside an API controller but can't manage to make it work.

This is the custom data type I made

public class MinimalStatementModel
{
public int ActivityID { get; set; }
public string StatementCode { get; set; }
public string Value { get; set; }
public string Note { get; set; }
}

This is the HttpClient part

static async Task UpdateActivityStatement()
        {
            string uri = "/api/ExtraNet/UpdateActivityStatement";

            HttpClient client = new HttpClient();

            int ActivityId = 12345; //Aktivite Numarası
            string StatementCode = "123456";
            string Value = "Test";
            string Note = "Test";

            string token = ""

            client.BaseAddress = "address"
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));
            client.Timeout = TimeSpan.FromMinutes(30);


            var postData = "{ \"ActivityID\":\"" + ActivityId + "\"" + ","
                             +"\"StatementCode\":\"" + StatementCode + "\"" + ","
                             +"\"Value\":\"" + Value + "\"" +"," 
                             +"\"Note\":\"" + Note + "\"}";

            var content = new StringContent(postData, Encoding.UTF8, "application/json");

            HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Post, uri);
            message.Headers.Add("Authorization", string.Format("bearer {0}", token));
            message.Content = content;

            HttpResponseMessage response = await client.SendAsync(message);

            var responseJson = await response.Content.ReadAsStringAsync();

            Console.WriteLine(responseJson);
        }

and this is the part in API controller

public ResponseHelper UpdateActivityStatement(List<MinimalStatementModel> requestList)
        {
            //releveant codes
        }

I'm able to work with custom data types and HttpClient but a List of a custom data type took longer than I'd guess.

How can I manage to make this work?


Solution

  • Your JSON is a single object and not a list/array. Enclose the object in square brackets ("[]") to represent an collection.

    var postData = "[{ \"ActivityID\":" + ActivityId.ToString() + ","
                 +"\"StatementCode\":\"" + StatementCode + "\"" + ","
                 +"\"Value\":\"" + Value + "\"" +"," 
                 +"\"Note\":\"" + Note + "\"}]";