从多个控制器合并HttpGet方法

时间:2019-07-19 19:42:30

标签: c# asp.net-core asp.net-web-api

我正在开发一个ASP.NET Core网站,该网站向ASP.NET Web API发出请求。在打开视图之前,我的网站控制器中有一些地方当前正在执行多个请求以填充下拉列表和列表:

// Populate countryies, states and cities, to populate dropdown lists
var countries = await client.GetAsync("countries");
if (countries.IsSuccessStatusCode)
{
    viewModel.Countries = await countries.Content.ReadAsAsync<List<Country>>();
}

var states = await client.GetAsync("states");
if (states.IsSuccessStatusCode)
{
    viewModel.States = await states.Content.ReadAsAsync<List<State>>();
}

var cities = await client.GetAsync("cities");
if (cities.IsSuccessStatusCode)
{
    viewModel.Cities = await cities.Content.ReadAsAsync<List<City>>();
}

var residues = await client.GetAsync("residues");
if (residues.IsSuccessStatusCode)
{
    viewModel.Residues = await residues.Content.ReadAsAsync<List<SiteResidue>>();
}

return View(viewModel);

我必须分别发出这些请求,因为在我的API中,每个表都有控制器(CountriesController,StatesController,CitiesController ...),并且这些表的HttpGet方法在各个控制器中声明。从结构上看,这似乎是正确的,但是它发出的请求不是最优的,因为我可能只发出一个请求以同时接收所有数据并减少加载时间。

我应该如何构造我的API控制器,以便可以将所有这些请求转换为一个?即使没有该名称的表,我也应该创建一个“ CountriesStatesCitiesControllers”吗?

1 个答案:

答案 0 :(得分:2)

由于它们都是异步调用,因此您可以同时进行调用并等待所有调用完成:

var countriesTask = client.GetAsync("countries");
var statesTask = client.GetAsync("states");
var citiesTask = client.GetAsync("cities");
var residuesTask = client.GetAsync("residues");

await Task.WhenAll(countriesTask, statesTask, citiesTask, residuesTask);

viewModel.Countries = countriesTask.Result.Content.ReadAsAsync<List<Country>>();
viewModel.States = statesTask.Result.Content.ReadAsAsync<List<State>>();
viewModel.Cities = citiesTask.Result.Content.ReadAsAsync<List<City>>();
viewModel.Residues = residuesTask.Result.Content.ReadAsAsync<List<SiteResidue>>();

return View(viewModel);