服务器端Blazor不提供HttpClient进行注入 [英] Server-side Blazor does not provide HttpClient for injection
问题描述
当我尝试注入HttpClient时,在剃须刀页面上出现错误:
I get an error in razor page when I try to inject HttpClient:
未处理的承诺拒绝:错误:System.InvalidOperationException:无法为type的属性'Http'提供值.没有类型为"System.Net.Http.HttpClient"的注册服务.
Unhandled Promise Rejection: Error: System.InvalidOperationException: Cannot provide a value for property 'Http' on type . There is no registered service of type 'System.Net.Http.HttpClient'.
请仔细检查并提供反馈.
Kindly review and give feedback.
推荐答案
如果您向代码段提供要执行的操作,将更容易回答您的问题.但是没问题.现在,我将向您展示一个示例,您需要执行哪些操作才能使用DI注入服务.
it would be easier to answer your question if you give code-snippets what you are trying to do. But ok. For now I will show you an example what you have to do, to inject a Service with DI.
ChartDataService.cs
namespace MyBlazorApp.Services
{
public class ChartDataService: IChartDataService
{
public HttpClient httpClient;
public ChartDataService(HttpClient httpClient)
{
this.httpClient = httpClient;
}
public async Task < IEnumerable < ChartData >> GetChartData()
{
return await httpClient.GetJsonAsync < ChartData[] > ($ "myUri");
}
}
}
IChartDataService.cs
namespace MyBlazorApp.Services
{
public interface IChartDataService
{
Task < IEnumerable < ChartData >> GetChartData();
}
}
Startup.cs
// other
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
// some services
services.AddHttpClient < IChartDataService, ChartDataService > (client =>
{
client.BaseAddress = new Uri(myBaseUri);
});
}
MyRazorPage.razor.cs (when using code Behind)
[Inject] private IChartDataService ChartDataService { get; set; }
or in
MyRazorPage.razor
@code
{
[Inject] private IChartDataService ChartDataService { get; set; }
}
then in your code - block or code - behind file u can use something like this,
for example, in an async function..
protected override async Task OnInitializedAsync()
{
chartData = await ChartDataService.MakeChartData();
}
这篇关于服务器端Blazor不提供HttpClient进行注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!