gpt4 book ai didi

.net - 服务器端 Blazor 不提供 HttpClient 进行注入(inject)

转载 作者:行者123 更新时间:2023-12-03 00:11:45 27 4
gpt4 key购买 nike

当我尝试注入(inject) HttpClient 时,我在 razor 页面中收到错误:

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'.

请查看并提供反馈。

最佳答案

如果您给出您想要执行的操作的代码片段,那么回答您的问题会更容易。但是没问题。现在,我将向您展示一个示例,您必须做什么,才能使用 DI 注入(inject)服务。

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();
}

关于.net - 服务器端 Blazor 不提供 HttpClient 进行注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55220269/

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