我的 ASP.Net MVC 控制器中有以下代码:
public ActionResult GetAnimals()
{
List<Dog> dogs = GetDogs("api/dogs).Result;
List<Cat> dogs = GetCats("api/cats).Result;
List<Horse> dogs = GetCats("api/cats).Result;
...
...
}
private async Task<List<Dog>> GetDogs(string requestUri)
{
String ret = "";
var client = new HttpClient();
client.BaseAddress = new Uri("http://theservice.com/");
var response = client.GetAsync(requestUri).Result;
if (response.IsSuccessStatusCode)
{
ret = await response.Content.ReadAsAsync<List<Dog>>();
}
else
{ }
return ret;
}
private async Task<List<Cat>> GetCats(string requestUri)
{
String ret = "";
var client = new HttpClient();
client.BaseAddress = new Uri("http://theservice.com/");
var response = client.GetAsync(requestUri).Result;
if (response.IsSuccessStatusCode)
{
ret = await response.Content.ReadAsAsync<List<Cat>>();
}
else
{ }
return ret;
}
如何避免一遍又一遍地重写 Get 方法,具体取决于返回类型。一定有聪明的办法!