Home > Net >  How to check the rest empty response in dotnet
How to check the rest empty response in dotnet

Time:10-19

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);

CodePudding user response:

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

CodePudding user response:

Why did not use http client?

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

  • Related