C# CS1929&x9';IHttpClientFactory&x27;不包含';GetFromJsonAsync';
我在Blazor服务器项目中的Razor组件页面Index.Razor上收到消息“CS1929-'IHttpClientFactory'不包含'GetFromJsonAsync'的定义”。我正在尝试发出http请求以将组件连接到数据库 以下是index.razor中的代码:C# CS1929&x9';IHttpClientFactory&x27;不包含';GetFromJsonAsync';,c#,blazor,crud,blazor-server-side,httpclientfactory,C#,Blazor,Crud,Blazor Server Side,Httpclientfactory,我在Blazor服务器项目中的Razor组件页面Index.Razor上收到消息“CS1929-'IHttpClientFactory'不包含'GetFromJsonAsync'的定义”。我正在尝试发出http请求以将组件连接到数据库 以下是index.razor中的代码: @page "/people" @inject IHttpClientFactory httpClientFactory <h3>People</h3> @if (people
@page "/people"
@inject IHttpClientFactory httpClientFactory
<h3>People</h3>
@if (people == null)
{<text>Loading...</text>}
else if (people.Length == 0)
{ <text>No people have been added to this database.</text>}
else
{
<table>
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>First Name</th>
<th>Last Name</th>
<th>Phone Number</th>
<th>Email ID</th>
<th>Address</th>
</tr>
</thead>
<tbody>
@foreach (var person in people)
{
<tr>
<td><a>Edit</a><button>Delete</button></td>
<td>@person.ID</td>
<td>@person.Title</td>
<td>@person.FirstName</td>
<td>@person.LastName</td>
<td>@person.PhoneNumber</td>
<td>@person.Email</td>
<td>@person.Address</td>
</tr>
}
</tbody>
</table>
}
@code {
Person[] people { get; set; }
protected override async Task OnInitializedAsync()
{
await LoadPeople();
}
async Task LoadPeople() => people = await httpClientFactory.GetFromJsonAsync<Person[]>("api/people");
}
解决这个问题的最佳方法是什么?每次尝试连接http时,我都会遇到一个新问题。您必须安装System.Net.http.Json包 为System.Net.Http.HttpClient和System.Net.Http.HttpContent提供扩展方法,这些扩展方法使用System.Text.Json执行自动序列化和反序列化 请在nuget控制台中执行以下操作:
Install-Package System.Net.Http.Json -Version 3.2.1
代码示例:
public void ConfigureServices(IServiceCollection services)
{
// Chnage the url to yours
services.AddHttpClient("ServerAPI", client => client.BaseAddress =
new Uri("https://localhost:44371/"));
services.AddTransient(sp =>
sp.GetRequiredService<IHttpClientFactory>
().CreateClient("ServerAPI"));
}
我已经有System.Net.Http.Json,它在我的“_imports.razor”文件中。我想它是预装的。
public void ConfigureServices(IServiceCollection services)
{
// Chnage the url to yours
services.AddHttpClient("ServerAPI", client => client.BaseAddress =
new Uri("https://localhost:44371/"));
services.AddTransient(sp =>
sp.GetRequiredService<IHttpClientFactory>
().CreateClient("ServerAPI"));
}
@inject HttpClient httpClient