3

I wonder why it returns null when I tried in postman it has data returns. Here is my code.

public async Task<List<HomeViewModel>> GetUserJobs(LoginResult token)
{
    var result = new List<HomeViewModel>();
    string url = "JobHeaders?userName=" + token.userName;
    HttpResponseMessage httpResponse =  await _requestHelper.GetHttpResponse(url, token.access_token);
    result = GetJobResponse(httpResponse);
    return result;
}

Get async function

public async Task<HttpResponseMessage> GetHttpResponse(string requestUri, string token)
{
    using (var client = CreateHttpClient(token))
    {
        try
        {
            HttpResponseMessage response = await client.GetAsync(requestUri);

            return response;
        }
        catch (HttpRequestException ex)
        {
            throw new HttpRequestException(ex.Message);
        }
    }
}

Adding the base address

private HttpClient CreateHttpClient(string authorization="")
{
    var client = new HttpClient();
    string baseAddress = WebApiBaseAddress;
    if (string.IsNullOrEmpty(baseAddress))
    {
        throw new HttpRequestException("There is no base address specified in the configuration file.");
    }

    client.Timeout = new TimeSpan(0, 5, 59);
    client.BaseAddress = new Uri(baseAddress);
    //client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Add("Authorization", string.Format("bearer {0}", authorization));
    client.DefaultRequestHeaders.Add("Accept", "application/json");
    client.DefaultRequestHeaders.Add("LegacyUse", "true");
    return client;
}

Deserialize JSON

private List<HomeViewModel> GetJobResponse(HttpResponseMessage response)
{
    var result = new List<HomeViewModel>();
    if (response.IsSuccessStatusCode)
    {
        var jsonString = response.Content.ReadAsStringAsync();
        jsonString.Wait();
        if (jsonString.IsCompleted)
        {
            try
            {
                var data = JObject.Parse(jsonString.Result);
                result = JsonConvert.DeserializeObject<List<HomeViewModel>>(data.ToString());
                result.FirstOrDefault().isSuccess = true;
                result.FirstOrDefault().TotalJobs = result.Count();
                result.FirstOrDefault().TotalOpenJobs = result.Where(x => x.JobStatus == "Picked_Up" || x.JobStatus == "Picked Up").ToList().Count();
            }
            catch (Exception ex)
            {
                result.FirstOrDefault().message = ex.Message;
                result.FirstOrDefault().isSuccess = false;
            }
        }
        return result;
    }
    else
    {
        return null;
    }
}

Image below is the httpresponse where the content is null and the status code is true

enter image description here

This is the response from Postman enter image description here

I did breakpoint the web API as well since it is only in my local then it actually has data.

Nkosi
  • 235,767
  • 35
  • 427
  • 472
Jen143
  • 815
  • 4
  • 17
  • 42
  • 1
    Those blocking calls are going to cause you problems. have `GetJobResponse` return task and await the response string. Avoid mixing async await and blocking calls like `.Wait()` or `.Result`. – Nkosi Mar 13 '18 at 02:18
  • I have tried not using async but same response. It is null. – Jen143 Mar 13 '18 at 02:27

2 Answers2

2

Avoid mixing async/await and blocking calls like .Wait() or .Result

Refactor your code to be async all the way through

private async Task<List<HomeViewModel>> GetJobResponse(HttpResponseMessage response) {
    var result = new List<HomeViewModel>();
    if (response.IsSuccessStatusCode) {
        var jsonString = await response.Content.ReadAsStringAsync();
        try {
            result = JsonConvert.DeserializeObject<List<HomeViewModel>>(jsonString);
            if(result != null && result.Count > 0) {
                result.FirstOrDefault().isSuccess = true;
                result.FirstOrDefault().TotalJobs = result.Count();
                result.FirstOrDefault().TotalOpenJobs = result.Where(x => x.JobStatus == "Picked_Up" || x.JobStatus == "Picked Up").Count();
            }
        } catch (Exception ex) {
            var item = new HomeViewModel {
                message = ex.Message,
                isSuccess = false
            };
            result.Add(item);
        }                
        return result;
    } else {
        return null;
    }
}

And used

public async Task<List<HomeViewModel>> GetUserJobs(LoginResult token) {
    var result = new List<HomeViewModel>();
    string url = "JobHeaders?userName=" + token.userName;
    HttpResponseMessage httpResponse =  await _requestHelper.GetHttpResponse(url, token.access_token);
    result = await GetJobResponse(httpResponse);
    return result;
}

Finally I would suggest you review how HttpClient should be used. Creating a new instance for each request is not advised.

Nkosi
  • 235,767
  • 35
  • 427
  • 472
0

Your response does have content. It's the second row in your image from the Locals window. It's a StreamContent object.

What you're looking at instead is the content of your request. That has no content, because HTTP GET requests do not have a body (in general).

yaakov
  • 5,552
  • 35
  • 48
  • A perfectly valid point that directly answers the question. Not sure why it has downvotes. If you want learn how to use C# and HttpClient, check out [the other answer](https://stackoverflow.com/a/49247460/1296733), otherwise, this is the correct answer. – Thick_propheT May 16 '23 at 20:02