【发布时间】:2020-11-11 23:05:13
【问题描述】:
我正在尝试从 HttpClient 获取异步数据,并将此数据作为单例添加到 Startup.cs 中的 ConfigureServices
public static class SolDataFill
{
static HttpClient Client;
static SolDataFill()
{
Client = new HttpClient();
}
public static async Task<SolData> GetData(AppSettings option)
{
var ulr = string.Format(option.MarsWheaterURL, option.DemoKey);
var httpResponse = await Client.GetAsync(ulr);
var stringResponse = await httpResponse.Content.ReadAsStringAsync();
var wheather = JsonConvert.DeserializeObject<SolData>(stringResponse);
return wheather;
}
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(Configuration);
var settings = Configuration.GetSection("NasaHttp") as AppSettings;
var sData = await SolDataFill.GetData(settings);
services.AddSingleton<SolData>(sData);
}
有一个错误:可以仅将 await 与 async 一起使用。如何将数据从异步方法添加到单例?
【问题讨论】:
-
你试过
var sData = SolDataFill.GetData(settings).Result;吗? -
你可以使用
GetAwaiter().GetResult()同步运行这个方法
标签: c# .net-core asp.net-core-3.0