gpt4 book ai didi

C# HttpClient 返回状态 WaitingForActivation

转载 作者:行者123 更新时间:2023-12-04 00:20:08 26 4
gpt4 key购买 nike

我只有一种 Api Request 方法如下

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;
}

当我尝试从我的 MainClass 调用它时,第一个调用 (a) 工作正常,但 b、c 和 d 它们都返回给我 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();
}

我怎样才能得到 b,c 和 d 的结果?

最佳答案

您应该等待调用,因为您只能在 async 方法中执行此操作,而不能在构造函数中执行,因此您应该将代码移至方法或事件处理程序中:

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();
}

关于C# HttpClient 返回状态 WaitingForActivation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61342443/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com