0

I am using RestSharp for API calling in dotnet core. I have one endpoint on which sometimes I am getting empty response {} and when there is data it returns me the data.

I want to add this empty {} response check so currently, I am doing so.

var request = new RestRequest($"endpoint", Method.Get);
request.AddHeader("Content-Type", "application/json");
var response = client.Execute<EmployeeDetails>(getRequest);

  • 1
    Please reformulate your post into a definitively answerable question or consider removing it and asking in a different venue. Asking for "the correct way" leads to opinion based answers which will be downvoted or removed. – possum Oct 13 '22 at 11:16
  • 1
    Properly designed API should return appropriate Http codes in different situations. If you request a single object then API should return 404 if such object not found. At the client side you should check `RestResponse.ResponseStatus` and decide how to handle 404 or other Http codes. – BorisR Oct 13 '22 at 12:19
  • @BorisR you are correct. However, OP may not have the means/access to change this API. – Alexandru Clonțea Oct 13 '22 at 13:10
  • Hello, was the issue resolved? Have you tired the solution provided? Please let me know if any further assistance required on this. – Md Farid Uddin Kiron Nov 02 '22 at 10:06

2 Answers2

0

How to check the rest empty response in dotnet

Altough, your code snippet were incomplete to simulate your issue. However, you could check your response data collection by simply checking response.Data.Count == 0.

Here is the complete example.

Asp.net Core C# Example:

public  IActionResult GetAll()
        {
           
            HttpClientHandler clientHandler = new HttpClientHandler();
            clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };

            HttpClient httpClient = new HttpClient(clientHandler);
            httpClient.BaseAddress = new Uri("https://localhost:44361/");

            var restClient = new RestClient(httpClient);
            var request = new RestRequest("UserLog/GetData", Method.Get) { RequestFormat = DataFormat.Json };
            var response = restClient.Execute<List<QueryExecutionModel>>(request);


            if (response.Data.Count == 0)
            {
                var emptyObject = new QueryExecutionModel();
                return Ok(emptyObject);
            }
             



            return Ok(response.Data);
        }

Note: When I am getting qualified response I am directly returning the response as Ok(response.Data). While I am getting the response model count = 0 then I am returing the empty model by new QueryExecutionModel()

Output:

enter image description here

Md Farid Uddin Kiron
  • 16,817
  • 3
  • 17
  • 43
0

Why did not use http client?

Plese Check it out! https://www.c-sharpcorner.com/article/calling-web-api-using-httpclient/