在ASP.NET Core中添加HTTP客户端是很常见的。在许多情况下,调用多个API路由时,可以使用泛型来减少重复的代码。以下是一个使用泛型的示例:
services.AddHttpClient();
services.AddTransient();
public class MyHttpClient
{
private readonly HttpClient _httpClient;
public MyHttpClient(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task GetAsync(string uri)
{
var response = await _httpClient.GetAsync(uri);
response.EnsureSuccessStatusCode();
var responseText = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject(responseText);
return result;
}
}
public class HomeController : Controller
{
private readonly MyHttpClient _myHttpClient;
public HomeController(MyHttpClient myHttpClient)
{
_myHttpClient = myHttpClient;
}
public async Task Index()
{
var data = await _myHttpClient.GetAsync>(uri);
return View(model);
}
}
这样,您就可以使用一个通用的方法来处理多个API调用。请注意,此代码示例仅用于说明目的。在实际应用程序中,您可能需要处理异常,添加身份验证,传递HTTP请求头等。