我正试图在blazor(客户端(启动期间调用一个api,以将语言翻译加载到ILocalizer中。
在这一点上,我试图得到。得到请求的结果blazor在标题中抛出了错误。
这可以通过在程序.cs 中调用此方法来复制
private static void CalApi()
{
try
{
HttpClient httpClient = new HttpClient();
httpClient.BaseAddress = new Uri(@"https://dummy.restapiexample.com/api/v1/employees");
string path = "ididcontent.json";
string response = httpClient.GetStringAsync(path)?.Result;
Console.WriteLine(response);
}
catch(Exception ex)
{
Console.WriteLine("Error getting api response: " + ex);
}
}
避免.Result
,它可以很容易地死锁。出现此错误是因为单线程Web程序集不支持该机制。我认为这是一个特色。如果它能在监视器上等待,它就会冻结。
private static async Task CalApi()
{
...
string response = await httpClient.GetStringAsync(path);
...
}
所有事件和生命周期方法重写都可以是Blazor中的async Task
,所以您应该能够将其放入中
在程序.cs 中
public static async Task Main(string[] args)
{
......
builder.Services.AddSingleton<SomeService>();
var host = builder.Build();
...
在这里调用您的代码,但使用等待
var httpClient = host.Services.GetRequiredService<HttpClient>();
string response = await httpClient.GetStringAsync(path);
...
var someService = host.Services.GetRequiredService<SomeService>();
someService.SomeProperty = response;
await host.RunAsync();
这是一个最好的例子:
var client= new ProductServiceGrpc.ProductServiceGrpcClient(Channel);
category = (await client.GetCategoryAsync(new GetProductRequest() {Id = id})).Category;