简体   繁体   English

无法使用DI解析类型为'System.Net.Http.HttpClient'的服务

[英]Unable to resolve service for type 'System.Net.Http.HttpClient' using DI

I writing phone verification functional via Twilio and using System.Net.Http.HttpClient 我通过Twilio并使用System.Net.Http.HttpClient编写了电话验证功能

I inject it in AppService like this 我像这样在AppService中注入

 public class TwilioVerifyClientAppService: IVerifyPhone
    {
    private readonly HttpClient _client;

    public TwilioVerifyClientAppService(HttpClient client)
    {
        _client = client;
    }

    public async Task<TwilioSendVerificationCodeResponse> StartVerification(int countryCode, string phoneNumber)
    {
        var requestContent = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("via", "sms"),
            new KeyValuePair<string, string>("country_code", countryCode.ToString()),
            new KeyValuePair<string, string>("phone_number", phoneNumber),
        });

        var response = await _client.PostAsync("protected/json/phones/verification/start", requestContent);

        var content = await response.Content.ReadAsStringAsync();

        // this will throw if the response is not valid
        return JsonConvert.DeserializeObject<TwilioSendVerificationCodeResponse>(content);
    }


    public async Task<TwilioCheckCodeResponse> CheckVerificationCode(int countryCode, string phoneNumber,
        string verificationCode)
    {
        var queryParams = new Dictionary<string, string>()
        {
            {"country_code", countryCode.ToString()},
            {"phone_number", phoneNumber},
            {"verification_code", verificationCode},
        };

        var url = QueryHelpers.AddQueryString("protected/json/phones/verification/check", queryParams);

        var response = await _client.GetAsync(url);

        var content = await response.Content.ReadAsStringAsync();

        // this will throw if the response is not valid
        return JsonConvert.DeserializeObject<TwilioCheckCodeResponse>(content);
    }
}

} }

When I try to run method, I get this error 当我尝试运行方法时,出现此错误

Here is how I call this method in controller 这是我在控制器中调用此方法的方式

     [ApiController]
    [Route("api/[controller]/[action]")]
    public class ProfileController : ControllerBase
    {
        private readonly IUserProfile _profileAppService;
        private readonly UserManager<AppUser> _userManager;
        private readonly IFileUpload _fileUpload;
        private readonly IVerifyPhone _verifyPhone;

        public ProfileController(IUserProfile profileAppService,
            UserManager<AppUser> userManager, IFileUpload fileUpload, IVerifyPhone verifyPhone)
        {
            _profileAppService = profileAppService;
            _userManager = userManager;
            _fileUpload = fileUpload;
            _verifyPhone = verifyPhone;
        }
[Authorize]
        [HttpPost]
        public async Task<IActionResult> ConfirmCodeSend([FromForm] PhoneInputDto input)
        {
            var result = await _verifyPhone.StartVerification(input.DialingCode, input.PhoneNumber);
            if (result.Success)
            {
                return Ok("Code sent");
            }

            return BadRequest();
        }

        [Authorize]
        [HttpPost]
        public async Task<IActionResult> ConfirmCodeCheck([FromForm] PhoneInputDto input)
        {
            var result =
                await _verifyPhone.CheckVerificationCode(input.DialingCode, input.PhoneNumber, input.VerificationCode);
            if (result.Success)
            {
                return Ok("Phone verified");
            }

            return BadRequest();
        }
    }
}

An unhandled exception occurred while processing the request. 处理请求时发生未处理的异常。 InvalidOperationException: Unable to resolve service for type 'System.Net.Http.HttpClient' while attempting to activate 'TooSeeWeb.Infrastructure.AppServices.UserProfile.TwilioVerifyClientAppService'. InvalidOperationException:尝试激活“ TooSeeWeb.Infrastructure.AppServices.UserProfile.TwilioVerifyClientAppService”时,无法解析类型为“ System.Net.Http.HttpClient”的服务。

In Startup.cs I register my interface like this Startup.cs我这样注册我的界面

services.AddScoped<IVerifyPhone, TwilioVerifyClientAppService>();

I tried to write this in Startup.cs 我试图在Startup.cs中写这个

services.AddHttpClient<TwilioVerifyClientAppService>();

But I still see this error. 但我仍然看到此错误。

How I can solve this? 我该如何解决?

You registered the class as a typed client but not the interface, yet try to inject the interface as a dependency into the controller. 您将该类注册为类型化的客户端,但未将其注册为接口,但是尝试将接口作为依赖项注入到控制器中。

Update the typed client registration to include the interface 更新类型化的客户端注册以包括接口

services.AddHttpClient<IVerifyPhone, TwilioVerifyClientAppService>();

provided TwilioVerifyClientAppService is derived from IVerifyPhone 提供的TwilioVerifyClientAppService源自IVerifyPhone

public class TwilioVerifyClientAppService: IVerifyPhone {
    //...
}

and remove the scoped registration 并删除范围注册

services.AddScoped<IVerifyPhone, TwilioVerifyClientAppService>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法解析“System.Net.Http.HttpClient”类型的服务 - Unable to resolve service for type 'System.Net.Http.HttpClient' 尝试激活时无法解析类型“System.Net.Http.HttpClient”的服务 - Unable to resolve service for type 'System.Net.Http.HttpClient' while attempting to activate 使用 System.Net.Http.HttpClient 的并行 HTTP 请求 - Parallel HTTP requests using System.Net.Http.HttpClient System.Net.Http.HttpClient如何选择身份验证类型? - How does the System.Net.Http.HttpClient select authentication type? 无法使用System.Net.Http.HttpClient从REST Web服务获得有效响应 - Can't get a valid response from a REST web service using System.Net.Http.HttpClient System.Net.Http.HttpClient缓存 - System.Net.Http.HttpClient cache System.Net.Http.HttpClient 缓存行为 - System.Net.Http.HttpClient caching behavior 自动重试System.Net.Http.HttpClient - Automatic retry for the System.Net.Http.HttpClient Autofac 和 IHttpClientFactory:无法解析参数“System.Net.Http.HttpClient httpClient” - Autofac and IHttpClientFactory: Cannot resolve parameter 'System.Net.Http.HttpClient httpClient' 提供带有System.Net.Http.HttpClient和MVC的AntiForgery令牌 - Provide AntiForgery Token with System.Net.Http.HttpClient and MVC
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM