You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Blazor Server中IHttpClientFactory未注册报错及POST请求问题

解决Blazor Server中IHttpClientFactory未注册及POST请求携带凭据问题

一、解决"IHttpClientFactory未注册"报错

核心问题是服务注册顺序错误:builder.Services.AddHttpClient()被写在了builder.Build()和app.Run()之后,此时服务容器已构建完成,注册的服务无法生效。

修改后的Program.cs代码:

// 先注册HttpClient服务
builder.Services.AddHttpClient();

var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}  

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

app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.Run();

二、完善POST请求,携带用户名和密码

当前代码仅创建了POST请求框架,未添加包含用户名密码的请求体。以下是两种常见的提交方式:

方式1:表单格式提交(application/x-www-form-urlencoded)

修改组件的OnInitializedAsync方法:

private IEnumerable<Yolo> test = Array.Empty<Yolo>();
private bool getBranchesError;

protected override async Task OnInitializedAsync()
{
    var request = new HttpRequestMessage(HttpMethod.Post, "https://url.com");
    request.Headers.Add("Accept", "application/vnd.github.json");
    request.Headers.Add("User-Agent", "HttpClientFactory-Sample");

    // 组装用户名密码的表单数据
    var formData = new Dictionary<string, string>
    {
        { "username", "你的用户名" },
        { "password", "你的密码" }
    };
    request.Content = new FormUrlEncodedContent(formData);

    var client = ClientFactory.CreateClient();
    var response = await client.SendAsync(request);

    if (response.IsSuccessStatusCode)
    {
        using var responseStream = await response.Content.ReadAsStreamAsync();
        test = await JsonSerializer.DeserializeAsync<IEnumerable<Yolo>>(responseStream);
    }
    else
    {
        getBranchesError = true;
    }
}

// 遵循C#命名规范,类名改为PascalCase
public class Yolo
{
    [JsonPropertyName("name")]
    public string Name { get; set; }
}

方式2:JSON格式提交(application/json)

若API要求JSON格式接收凭据,替换请求体部分:

// 新增凭据实体类
public class Credentials
{
    public string Username { get; set; }
    public string Password { get; set; }
}

// 在OnInitializedAsync中替换请求体代码:
var credentials = new Credentials
{
    Username = "你的用户名",
    Password = "你的密码"
};
request.Content = new StringContent(
    JsonSerializer.Serialize(credentials),
    Encoding.UTF8,
    "application/json");

三、其他优化点

  • 移除shouldRender变量:Blazor组件在OnInitializedAsync执行完成后会自动触发渲染,无需手动控制。
  • 类名调整为Yolo,符合C# PascalCase命名规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 13:01:55