CAD.Dev
CAD.Dev

Reputation: 187

HttpClient GetAsync not working as expected

When testing my web API with Postman my API get executes fine!

When it comes to running the code with HttpClient in my client application the code executes without error but without the expected result on the server. What could be happening?

From my client application:

private string GetResponseFromURI(Uri u)
{
    var response = "";
    HttpResponseMessage result;
    using (var client = new HttpClient())
    {
        Task task = Task.Run(async () =>
        {
            result = await client.GetAsync(u);
            if (result.IsSuccessStatusCode)
            {
                response = await result.Content.ReadAsStringAsync();
            }
        });
        task.Wait();
    }
    return response;
}

Here is the API controller:

[Route("api/[controller]")]
public class CartsController : Controller
{
    private readonly ICartRepository _cartRepo;

    public CartsController(ICartRepository cartRepo)
    {
        _cartRepo = cartRepo;
    }

    [HttpGet]
    public string GetTodays()
    {
        return _cartRepo.GetTodaysCarts();
    }

    [HttpGet]
    [Route("Add")]
    public string GetIncrement()
    {
        var cart = new CountedCarts();
        _cartRepo.Add(cart);

        return _cartRepo.GetTodaysCarts();
    }

    [HttpGet]
    [Route("Remove")]
    public string GetDecrement()
    {
        _cartRepo.RemoveLast();
        return _cartRepo.GetTodaysCarts();
    }


}

Note these API calls work as expected when called from Postman.

Upvotes: 5

Views: 41289

Answers (5)

Abhinesh Maddala
Abhinesh Maddala

Reputation: 21

Since you are able to hit the API endpoint with Postman, you should be able to get the working code of HttpClient for the same in Postman. Just click "</>" on the right-hand side. It gives code in many languages including C#'s HttpClient

Upvotes: 0

niek tuytel
niek tuytel

Reputation: 1179

Simple sample used to get page data.

public string GetPage(string url)
{
    HttpResponseMessage response = client.GetAsync(url).Result;

    if (response.IsSuccessStatusCode)
    {
        string page = response.Content.ReadAsStringAsync().Result;
        return "Successfully load page";
    }
    else
    {
        return "Invalid Page url requested";
    }
}

Upvotes: 1

Joe
Joe

Reputation: 2601

You shouldn't use await with client.GetAsync, It's managed by .Net platform, because you can only send one request at the time.

just use it like this

var response = client.GetAsync("URL").Result;  // Blocking call!

            if (response.IsSuccessStatusCode)
            {
                // Parse the response body. Blocking!
                var dataObjects = response.Content.ReadAsAsync<object>().Result;

            }
            else
            {
                var result = $"{(int)response.StatusCode} ({response.ReasonPhrase})";
               // logger.WriteEntry(result, EventLogEntryType.Error, 40);
            }

Upvotes: 24

user3164339
user3164339

Reputation: 166

I've had a problem with chace control when using httpclient.

HttpBaseProtocalFilter^ filter = ref new HttpBaseProtocolFilter();
filter->CacheControl->ReadBehavior = Windows::Web::Http::Filters::HttpCacheReadBehavior::MostRecent;
HttpClient^ httpClient = ref new HttpClient(filter);

I'm not really sure what the expected results are or what results your getting at all so this is really just a guessing game right now.

When I POST something using HttpClient I found adding headers by hand seemed to work more often than using default headers.

auto httpClient = ref new HttpClient();
Windows::Web::Http::Headers::HttpMediaTypeHeaderValue^ type = ref new Windows::Web::http::Headers::HttpMediaTypeHeaderValue("application/json");
content->Headers->ContentType = type;

If I don't do these 2 things I found, for me anyways, that half the time my web requests were either not actually being sent or the headers were all messed up and the other half of the time it worked perfectly.

I just read a comment where you said it would only fire once, that makes me think it is the cachecontrol. I think what happens is something (Windows?) sees 2 requests being sent that are the exact same, so to speed things up it just assumes the same answer and never actually sends the request a 2nd time

Upvotes: 0

Win
Win

Reputation: 62260

You are doing fire-and-forget approach. In your case, you need to wait for the result.

For example,

static async Task<string> GetResponseFromURI(Uri u)
{
    var response = "";
    using (var client = new HttpClient())
    {
        HttpResponseMessage result = await client.GetAsync(u);
        if (result.IsSuccessStatusCode)
        {
            response = await result.Content.ReadAsStringAsync();
        }
    }
    return response;
}

static void Main(string[] args)
{
    var t = Task.Run(() => GetResponseFromURI(new Uri("http://www.google.com")));
    t.Wait();

    Console.WriteLine(t.Result);
    Console.ReadLine();
}

Upvotes: 9

Related Questions