首页 > 解决方案 > 我应该使用哪种类型的 IHttpClientFactory 方法将 HttpClient 添加到服务器端 Blazor?

问题描述

我正在使用 Blazor 和 Entity Framework Core 制作 Blazor 制作 CRUD 应用程序,但收到以下错误消息:

错误信息

下面是我的 Razor 组件中的代码:

@page "/people"
@inject HttpClient http

<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 http.GetFromJsonAsync<Person[]>("api/people");
}

下面是 Startup.cs 中的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using CuriousDriveTutorial.Data;
using Microsoft.Extensions.Options;
using Microsoft.EntityFrameworkCore;

namespace CuriousDriveTutorial
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDBContext>(Options => Options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            //services.AddHttpClient();
            services.AddRazorPages();
            services.AddServerSideBlazor();
            services.AddSingleton<WeatherForecastService>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapBlazorHub();
                endpoints.MapFallbackToPage("/_Host");
            });
        }
    }
}

我尝试添加services.AddHttpClient();,但没有任何区别,所以我删除了它。

我读到我需要使用 IHttpClientFactory 为服务器端 Blazor 发出 HTTP 请求,所以我找到了以下链接:

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.1#basic-usage

但是,我不确定我应该使用基本用法、命名客户端、类型客户端或生成客户端的方法。那么对于此类项目,哪种方法最好?

提前致谢。

PS:我是后端新手。

标签: c#httpblazorcrudblazor-server-side

解决方案


您缺少服务配置。只需将其添加到您的Startup课程中

public void ConfigureServices(IServiceCollection services)
    {
        ...
        services.AddHttpClient();
    }

推荐阅读