【发布时间】:2020-04-20 11:20:47
【问题描述】:
我正在开发一个 Blazor 项目,为了让我更容易理解这个问题,我们可以说我正在使用两种不同的服务来处理身份验证部分。它们与命名的 httpclient 一起注册在 configureservices 启动方法中。
services.AddHttpClient("XBOWServicesApi", c =>
{
c.BaseAddress = new Uri(XBOWServicesApi);
});
services.AddSingleton<IService1, Service1>();
services.AddSingleton<IService2, Service2>();
服务 1:包装 REST Api 中可用的所有功能。它使用通过实例化的 httpclientfactory 在构造函数中设置的 http 客户端。这需要使用 baseurl 和 Auth-header 设置才能工作。
public Service1(IHttpClientFactory clientFactory)
{
this.httpClient = clientFactory.CreateClient("XBOWServicesApi");
}
服务 2:使用自定义 AuthenticationStateProvider 处理登录/注销功能。它有自己的httpclient,所以我可以为http客户端设置Auth Header。构造函数的工作方式与服务 1 相同。
public Service2(IHttpClientFactory clientFactory)
{
this.httpClient = clientFactory.CreateClient("XBOWServicesApi");
}
这样建立的原因当然是我喜欢共享同一个http客户端,所以在登录/注销方法中设置时,服务1在与api通信时将具有正确的auth header。
但是,客户端工厂每次都提供一个新实例,所以这永远行不通。
任何想法如何处理这个?
/亨里克
【问题讨论】:
标签: c# asp.net-core service httpclient blazor