我正在创建一个DotNet6blazorwasm网站(核心托管),它使用B2C作为auth,但是遇到了http客户端的问题。
在program.cs中,我为DI提供了以下内容:
builder.Services.AddHttpClient<IBbtDataService, BbtDataService>(client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
.AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();应该将此Bbt服务注入到FetchBbtData页面后面的代码中,如下所示:
[Authorize]
public partial class FetchBbtData
{
[Inject]
public IBbtDataService BbtDataService { get; set; }
public IEnumerable<ClientOrg> ClientOrgs { get; set; }
protected async override Task OnInitializedAsync()
{
ClientOrgs = (await BbtDataService.GetClientOrgList()).ToList();
}
}BbtDataService的代码如下:
public class BbtDataService : IBbtDataService
{
private readonly HttpClient httpClient;
public BbtDataService(HttpClient httpClient)
{
httpClient = httpClient;
}
public async Task<IEnumerable<ClientOrg>> GetClientOrgList()
{
return await httpClient.GetFromJsonAsync<IEnumerable<ClientOrg>>($"api/clients");
}
}如果我在BbtDataService的构造函数上放置一个断点,请查看httpClient参数是有效的,并包含正确的基url。但是,当执行到达GetClientOrgList方法中的另一个断点时,私有只读字段httpClient的值为null --尽管这是在构造函数中设置的。
有人看到我哪里出错了吗?
发布于 2022-09-01 09:07:18
您正在将参数赋值给自身。添加2 _:
private readonly HttpClient _httpClient;
public BbtDataService(HttpClient httpClient)
{
_httpClient = httpClient;
}https://stackoverflow.com/questions/73566587
复制相似问题