![](/img/trans.png)
[英]Unable to resolve service for type 'System.Net.Http.HttpClient'
[英]Unable to resolve service for type 'System.Net.Http.HttpClient' while attempting to activate
我有 asp.net web api 3.1 应用程序,我有一个 Z594C103F2C6E04C3C3DAZ0 之类的应用程序,
public class WeatherForecastController : ControllerBase
{
private readonly HttpClient _httpClient;
public WeatherForecastController(HttpClient httpClient)
{
_httpClient = httpClient;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
现在在Startup
class 我已经注册了如下服务,
services.AddControllers().AddControllersAsServices();
services
.AddHttpClient<WeatherForecastController>((serviceProvider, client) =>
{
client.BaseAddress = new Uri("http://localhost:5002");
});
在应用程序启动中,我遇到了错误。 可能是什么问题?
InvalidOperationException: Unable to resolve service for type 'System.Net.Http.HttpClient' while attempting to activate 'WebApplication4.Features.Weather.WeatherForecastController'.
当您像这样注入 HttpClient 时,您正在尝试创建一个 Typed Client。
在您的情况下,您应该直接使用 HttpClientFactory 或使用命名客户端。
看看这个链接有 3 种注入 HttpClient 的方法: https://www.talkingdotnet.com/3-ways-to-use-httpclientfactory-in-asp-net-core-2-1/
(示例适用于 net core 2.1,但在 3.1 中的工作方式相同)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.