Search code examples
c#.netcontrollerwebapi

How Search in value API Content by use .net core controller


I used This controller for .net core:

  string url = "Url Here";
        private string customerApi;
        private object JsonRequestBehavior;

        [HttpGet]
        [Route("Getagent")]
        public async Task<ActionResult> Getagent(string search)
        {

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(url);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage response = await client.GetAsync(customerApi);
                if (response.IsSuccessStatusCode)
                {
                    string jsondata = await response.Content.ReadAsStringAsync();
                    return Content(jsondata, "application/json");
                }
            

                return Ok();
               
            }
        }

outputs values as array >> how I search in this array by API controller Web API


Solution

  • If the service at customerApi doesn't accept search strings and you want to do the search locally, you have to create a model that represent the data of the json. For example you get this json from the service:

    {
      "name": "John Smith",
      "id": 1,
      "age": 20,
      "tags": [
         "person", "male", "etc"
      ]
    }
    

    You have to create an object model like this:

    public class ServiceResponseModel {
      public string Name {get;set;}
      public int Id {get;set;}
      public int Age {get;set;}
      public string[] Tags {get;set;}
    }
    

    Then you can convert json into an array of these objects:

      string jsondata = await response.Content.ReadAsStringAsync();
      var responseObject=Newtonsoft.Json.JsonConvert.DeserializeObject(jsondata);
    

    If you got the object, you can search in its properties:

      var filteredResponseObject = responseObject.Where(x=>x.Name.Contains(search))