Blazor 서버 프로젝트의 Razor 구성 요소 페이지 Index.razor에 "CS1929- 'IHttpClientFactory'에 'GetFromJsonAsync'에 대한 정의가 포함되어 있지 않습니다."라는 메시지가 나타납니다. 구성 요소를 데이터베이스에 연결하기 위해 http 요청을하려고합니다.
다음은 index.razor의 코드입니다.
@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");
}
그리고 라인을 추가 services.AddHttpClient();
아래 public void ConfigureServices(IServiceCollection services)
Startup.cs에
오류는 단어 httpClientFactory
줄에 있습니다.async Task LoadPeople() => people = await httpClientFactory.GetFromJsonAsync<Person[]>
나는 그것을 아래로 바꾸려고 시도했지만 더 많은 오류가 발생하여 제거했습니다.
var http = httpClientFactory.CreateClient();
async Task LoadPeople() => people = await http.GetFromJsonAsync<Person[]("api/people");
이 문제를 해결하는 가장 좋은 방법은 무엇입니까? http를 연결하는 동안 이전 문제를 해결할 때마다 새로운 문제가 발생했습니다.
System.Net.Http.Json 패키지를 설치해야합니다 ...
System.Text.Json을 사용하여 자동 직렬화 및 역 직렬화를 수행하는 System.Net.Http.HttpClient 및 System.Net.Http.HttpContent에 대한 확장 메서드를 제공합니다.
너겟 콘솔에서 이것을 실행하십시오.
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"));
}
그리고 FetchData 페이지에서 :
@inject HttpClient httpClient
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다