Search code examples
c#asp.net-core.net-coredotnet-httpclient

How to call an API with an array of strings as the parameter


I have an endpoint like below:

[HttpPost("GetSchoolsDetails")]
public ActionResult<SchoolModel> GetSchoolsDetails(string[] SchoolsUuid)
{
    //some code
}

I'm trying to call this endpoint in some other place like below

var requestUrl = $"http://localhost:6200/api/Schools/GetSchoolsDetails";
var stringContent = new StringContent(SchoolsUuid.ToString());
using (var client = new HttpClient())
{
    client.DefaultRequestHeaders.Add("Authorization", _infrastructureAuthKey);
    response = client.PostAsync(requestUrl, stringContent);
    response.Wait();

}

But here I'm getting an "Unsupported Media Type" error.

Please let me know a better way to call the API by passing an array as a parameter.


Solution

    1. Serialize the SchoolsUuid array.

    2. Specify the Content-Type as "application/json".

    using System.Text;
    
    var stringContent = new StringContent(System.Text.Json.JsonSerializer.Serialize(SchoolsUuid)
        , Encoding.UTF8
        , "application/json");