无法找到错误解决方法,未注册Httpclient服务

问题描述 投票:0回答:1

我上周发现Blazor,对它的想法很着迷,我真的很喜欢它的结构或至少到目前为止的样子,我想我已经掌握了大部分阅读内容,所以我决定将小型Rss阅读器用作第一个测试演示应用程序,我基本上是基于本教程编写的,但仅具有极小的功能,例如仅获得一种类型的帖子,而不是教程中建议的所有帖子,该帖子于去年发布因此,当然不会出现复制和粘贴的情况,在Blazor上阅读了两天后,我开始但遇到一个奇怪的错误,并且经过2天的谷歌搜索还没有帮助我解决它,我希望任何人都可以在这里,对不起,如果我的语法不是最好的,我很清楚:)我希望它是可以理解的。enter image description hereenter image description here

enter image description here

@page "/latestposts"
@using Projectname.Shared.Models
@using System.Net.Http;
@inject HttpClient Http

<h4>C# Corner Latest Posts</h4>

@if (feeds == null)
{
    <p><em>Loading...</em></p>
}
else
{
    counter = 0;
    <table class='table'>
        <thead>
            <tr>
                <th>Sl.No.</th>
                <th>Post Title (With Link)</th>
                <th>Post Type</th>
                <th>Content</th>
                <th>Publish Date</th>
                <th>Author</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var feed in feeds)
            {
                counter++;
                <tr>
                    <td>@counter</td>
                    <td><NavLink [email protected] target="_blank">@feed.Title</NavLink></td>
                    <td>@feed.FeedType</td>
                    <td>@feed.Content</td>
                    <td>@feed.PublishDate</td>
                    <td>@feed.Author</td>
                </tr>
            }
        </tbody>
    </table>
}
@functions {
    Feed[] feeds;
    int counter;

    protected override async Task OnInitializedAsync()
    {
        feeds = null;
        feeds = await Http.GetJsonAsync<Feed[]>("/api/feeds/latestposts");
    }

}    
blazor
1个回答
0
投票

HttpClient是在托管的blazor上开箱即用的。在服务器端,您不需要Rest请求,因为后端与前端在同一位置。仅调用本地函数就足够了。

[在任何情况下,如果您需要HttpClient,例如要转到另一个站点,我建议您使用IHttpClientFactory

基本用法:

  1. 添加到服务:

    IHttpClientFactory
  2. 从DI获取:

    services.AddHttpClient();
    
  3. 提出要求:

    @inject IHttpClientFactory clientFactory
    

这是var client = _clientFactory.CreateClient(); var response = await client.SendAsync(request); if (response.IsSuccessStatusCode) { Branches = await response.Content .ReadAsAsync<IEnumerable<GitHubBranch>>(); } else { GetBranchesError = true; Branches = Array.Empty<GitHubBranch>(); }

在服务器上,IHttpClientFactory为发出概述在此处的一般HTTP请求提供了许多好处:Daniel Roth (Blazor product manager) talking about this issue

为Blazor WebAssembly Apps提供的HttpClient更加专业,并且经过专门配置,可以将请求发送回原始服务器。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.