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.

2
  • 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. Commented Mar 13, 2018 at 2:18
  • I have tried not using async but same response. It is null. Commented Mar 13, 2018 at 2:27

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

HttpClient has an async API and was meant to be used in a non blocking manner.
The problem I have with this code is the test for (response.IsSuccessStatusCode). I already know I am getting various error codes, including 400, 403, etc. However, when I try the same URI in a browser, I get the error code and I get XML response with more explanation of the issue. In my C# code, I can only get the response if the code is successful. How do I get the response regardless of the http code returned?
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).

1 Comment

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, otherwise, this is the correct answer.
0

recently I encounter same issue, finally realize root cause is & in URL.

when send request via postman client, it auto encode for you, & encode as %26

in program code, it is not encode which cause problem

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.