1

My ASP.NET Core 2.1 API app communicates with a third party API so I'm creating an ApiClient with generic CRUD methods in it.

The question is how I should handle a scenario where I got nothing from the API call -- I've seen cases where sometimes APIs return 204 but sometimes, they just return nothing at all with a status 200.

When I try to return null in case my response has nothing in it, I'm getting an error that says I can't do it because T may not be nullable.

Here's my code:

private readonly HttpClient _httpClient public MyClass(HttpClient httpClient) { _httpClient = httpClient; } public Task<T> GetMyData<T>() { try { var response = _httpClient.GetStringAsycn("https://someApiUrl"); // This is where I'm a bit stuck if(string.IsNullOrEmpty(response)) return null; // <<-- Can't return NULL! var data = JsonConvert.DeserializeObject<T>(response); return data; } catch(Exception e) { throw new Exception(e.Message); } } 
7
  • 3
    This article may help, try returning default(T) or restrict T to a reference type (stackoverflow.com/questions/302096/…) Commented Aug 15, 2018 at 20:42
  • Thank you! Both comments were useful and going with what @KirkLarkin suggested. If one of you posted your comment as answer, I can accept it. Thank you! Commented Aug 15, 2018 at 20:47
  • You can do Task.FromResult<T>(null). Commented Aug 15, 2018 at 20:47
  • Sorry, I deleted my comment as I didn't see @RyanWilson's first. Perhaps it's a duplicate? Commented Aug 15, 2018 at 20:47
  • @Sam I think you should just vote to close this as the answer is well documented in the link I provided. Thank you for considering us with an accepted answer though. Commented Aug 15, 2018 at 20:49

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.