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

时间:2019-10-11 13:04:38

标签: blazor

上周我发现了Blazor,只是它的想法让我着迷,我真的很喜欢它的结构或至少到目前为止的样子,我想我已经掌握了大部分阅读内容,因此我决定将小型Rss阅读器作为第一个测试演示应用程序,我基本上是基于本教程编写的,但是仅具有极小的功能性,例如仅获取一种类型的帖子,而不是教程中建议的所有帖子,该帖子最后发表今年当然不会是复制粘贴的情况,在Blazor上阅读了两天后,我开始但遇到一个奇怪的错误,而使用谷歌搜索2天仍没有帮助我解决它,我希望有人可以在这里,对不起,如果我的语法不是最好的话,我非常了解它:)我确实希望它是可以理解的。 enter image description here enter 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 href=@feed.Link 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");
    }

}    

1 个答案:

答案 0 :(得分:0)

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

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

基本用法:

  1. 添加到服务:

    services.AddHttpClient();
    
  2. 从DI获取:

    @inject IHttpClientFactory clientFactory
    
  3. 提出请求:

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

这是Daniel Roth (Blazor product manager) talking about this issue

  

在服务器上,IHttpClientFactory为发出以下概述的常规HTTP请求提供了许多好处:https://docs.microsoft.com/aspnet/core/fundamentals/http-requests

     

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

当然,您也可以使用HttpClient通过DI将其添加到服务中:

services.AddScoped<HttpClient>();