Search code examples
c#.net.net-core

How to call a endpoint in .Net core with request object


I've a endpoint like below in API 1

[HttpPost]
public ActionResult PostSchoolQuery([FromBody] SchoolQueryModel schoolQueryModel, [FromHeader] string authorization)
{

}

Here the Request Model class like below

public class SchoolQueryModel
{
 public List<Guid?> SchoolIds { get; set; }
 public List<Guid?> DistrictIds { get; set; }
}

And when I try to call the endpoint PostSchoolQuery from API 2 like below, In api-1 I'm always receiving null values

 public ActionResult GetUserSchools(SchoolQueryModel getSchoolsModel)
        {
           dynamic schoolDetails = null;          
            var requestContent = new JsonSerializer.Serialize(getSchoolsModel);
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", _infrastructureAuthKey);
                var responseTask = client.PostAsync("http://localhost:6200/api/post_school_query", requestContent);
                if (responseTask.Result.IsSuccessStatusCode)
                {
                    var readTask = responseTask.Result.Content.ReadAsAsync<JObject>();
                    readTask.Wait();
                    schoolDetails = readTask.Result;
                }
            }
  }

Let me know for a fix.


Solution

  • This fix works for me , I'm not sure why. if anyone knows please comment here

    In my api -2 I used JObject instead of a request model and PostAsJsonAsync directly

    public ActionResult GetUserSchools(JObject getSchoolsModel)
    {
    using (var client = new HttpClient())
    {
                   
    var responseTask = await client.PostAsJsonAsync( requestUrl, getSchoolsModel);
                    
    }
    
    }