I have only one method for Api Request as follow
private async Task<Site> getSiteAsync(string siteId)
{
Site site = null;
var response = await httpClient.SendAsync(
new HttpRequestMessage(HttpMethod.Get, httpClient.BaseAddress + $"api/sites/{siteId}"));
if (response.IsSuccessStatusCode)
{
var stream = await response.Content.ReadAsStreamAsync();
site = await JsonSerializer.DeserializeAsync<Site>(stream, serializerOptions);
}
return site;
}
When I try to call it from my MainClass the first call (a) works fine, but the b,c and d they all return me the Status = WaitingForActivation.
private readonly HttpClient httpClient = new HttpClient();
private readonly JsonSerializerOptions serializerOptions = new JsonSerializerOptions();
public MainWindow()
{
httpClient.BaseAddress = new Uri($"http://localhost:5000/MyApi/");
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
serializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
var a = getSiteAsync("0001"); << I only get the value of this call.
var b = getSiteAsync("0002");
var c = getSiteAsync("0003");
var d = getSiteAsync("0004");
InitializeComponent();
}
How can I get the Result of b,c and d ?
You should await the calls and since you can only do this in an async method and not in a constructor, you should move your code to a method or an event handler:
public MainWindow()
{
httpClient.BaseAddress = new Uri($"http://localhost:5000/MyApi/");
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
serializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
Loaded += async (s, e) =>
{
var a = await getSiteAsync("0001");
var b = await getSiteAsync("0002");
var c = await getSiteAsync("0003");
var d = await getSiteAsync("0004");
};
InitializeComponent();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With