You need to enable JavaScript to run this app. Server Side Blazor开发CRUD应用时IHttpClientFactory添加HttpClient的选型咨询
优惠活动
大模型
产品
解决方案
定价
更多

Server Side Blazor开发CRUD应用时IHttpClientFactory添加HttpClient的选型咨询

项目问题背景

我正在使用Blazor结合Entity Framework Core开发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; }

        // 该方法由运行时调用,可向容器中添加服务配置
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDBContext>(Options => Options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            //services.AddHttpClient();
            services.AddRazorPages();
            services.AddServerSideBlazor();
            services.AddSingleton<WeatherForecastService>();
        }

        // 该方法由运行时调用,用于配置HTTP请求处理管道
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // HSTS的默认有效期为30天,生产环境可根据需求调整
                app.UseHsts();
            }

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

            app.UseRouting();

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

我曾尝试在服务配置中添加 services.AddHttpClient();,但没有解决问题,因此将这行代码移除了。
我了解到Server-side Blazor场景下需要通过IHttpClientFactory发起HTTP请求,也查阅了ASP.NET Core关于HTTP请求的官方文档,但不确定当前项目应该选择基本用法、命名客户端、类型化客户端还是生成式客户端,请问哪种方式最适配当前项目场景?
注:我是后端开发新手。


问题解决指引

核心修复步骤

  1. 取消 Startup.cs 中 services.AddHttpClient() 的注释,将HttpClient服务注册到依赖注入容器中。你之前注释掉这行代码,导致组件注入HttpClient时找不到对应服务,是报错的核心原因
  2. Server-side Blazor内置的HttpClient默认适配站点根地址,你代码里写的相对路径 api/people 无需额外配置BaseAddress,即可正确发起本机接口请求

新手易踩的两个隐藏坑

  • 你当前的端点配置里只映射了Blazor Hub和前端回退路由,没有注册API控制器的端点路由,需要在 Configure 方法的端点配置块里加上 endpoints.MapControllers();,否则就算HttpClient配置正常,请求接口也会返回404
  • 你的表格结构存在列错位问题:表头共7个列项,循环渲染的单元格共8个(第一个单元格放置了编辑、删除操作按钮,后续依次对应了7个字段值),会导致渲染时列宽和内容不匹配。建议将操作列调整到表格最后一列,和表头的列顺序完全对齐

HttpClient选型建议

对于当前这类小型CRUD练手项目,直接用基础用法即可,不需要引入更复杂的配置:

  • 无需使用命名客户端:仅存在单一站点内的接口请求,没有对接多套外部API的需求
  • 无需使用类型化客户端:只有基础的增删改查请求,没有统一鉴权、日志拦截、错误封装的复杂逻辑需要落地
  • 无需使用生成式客户端:项目规模未达到需要自动生成强类型API代理的程度

后续如果项目复杂度提升,比如需要对接带鉴权的外部接口、加全链路请求日志,再根据需求升级配置即可。


内容的提问来源于stack exchange,提问作者user14394673

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.23 06:54:09