gpt4 book ai didi

asp.net-core - 在 .NET Core 2 中注册基于作用域的 HttpClient

转载 作者:行者123 更新时间:2023-12-04 13:45:28 29 4
gpt4 key购买 nike

我有 NET Core 2 Web API 应用程序。在此过程中,我必须调用客户端 A 的 API 来获取一些数据。所以我使用 HttpClient 来调用它。客户端 A 还要求我在 header 中传递用户 ID 和密码。

所以不是直接注入(inject) HttpClient我有包装HttpClient像下面这样的东西

public class ClientA : IClientA
{
private readonly HttpClient _httpClient;

public ClientA(HttpClient httpClient)
{
_httpClient = httpClient;
}

public async Task<string> GetData()
{
return await _httpClient.HttpGetAsync("someurl");
}
}

然后在 Service 中使用 ClientA
  public class MyService :IMyService
{
private readonly IClientA _clientA

public MyService(IClientA clientA)
{
_clientA= clientA
}

public void DoSomethig()
{
_clientA.GetData();
}
}

然后我在 Startup.cs 中注册所有内容
    public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IMyService, MyService>();

services.AddScoped(factory =>
{
Func<Task<IClientA>> provider = async () =>
{
using (var dbContext = factory.GetService<MyDBContext>())
{
// get userid and password from database here

var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("UserId",userid);
httpClient.DefaultRequestHeaders.Add("Password",password);
return new ClientA(httpClient);
}
};

return provider;
});
}

但是我收到错误

System.InvalidOperationException: Unable to resolve service for type 'System.Net.Http.HttpClient' while attempting to activate 'XXXXXXXXX.ClientA'. at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, ISet1 callSiteChain,
ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound) at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(Type
serviceType, Type implementationType, ISet
1 callSiteChain)



为简洁起见,删除了剩余的异常(exception)

请注意,在注册期间,我正在更新 HttpClient 的实例。并将其传递给 ClientA 类,因为我必须设置用户 ID 和密码。

为了摆脱上述错误,我可以使用 DI 框架使用 UserID 和 Password 注册 HttpClient,我想这会起作用。

但是,在这种情况下,如果有另一个客户端 ClientB,它接受 HttpClient,那么 DI 框架将注入(inject)具有用户 ID 和密码的相同 httpclient。这将产生安全问题,因为 ClientB 会在请求 header 中看到 ClientA 的凭据。
   public class ClientB(HttpClient client)
{
private readonly _httpClient;
public class ClientB(HttpClient client)
{
_httpClient = client;
}

public string CallClientB(string url)
{
// here ClientB will receive ClientA's credentials
return await _httpClient.HttpGetAsync(url);
}
}

最佳答案

您不想在作用域上下文中实例化 httpclient,即为每个请求创建一个 httpclient 实例,这不是该类的推荐使用模式。 (不会很好地扩展)。 https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/

为每个客户创建一个具有单独接口(interface)的单例(假设客户数量很少) - 可能在其实现中具有代码访问安全需求,具体取决于您的设置(启用身份模拟?)

这将 a) 很好地扩展 b) 每个客户每个应用程序实例/启动仅运行一次,以及 c) 强制执行使用访问检查。

此外,此答案与您的标题要求相关且相关 - HttpClient single instance with different authentication headers

关于asp.net-core - 在 .NET Core 2 中注册基于作用域的 HttpClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49120741/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com