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

Blazor登录组件HttpClient调用无响应问题排查求助

Blazor Login组件提交无反应且无HttpClient请求的排查方案

我在为微服务应用创建Blazor组件库时,Login.razor组件遇到提交表单后无任何反应、Chrome开发者工具网络面板看不到HttpClient发起的认证API请求的问题。预期流程是表单提交后调用认证API验证账号密码,获取JWT Token后在ASP.NET应用中创建会话。

相关代码

Login.razor组件代码

@inject NavigationManager NavigationManager
@inject HttpClient HttpClient
@inject IHttpContextAccessor HttpContextAccessor

<div class="container">
    <div class="row d-flex justify-content-center" style="padding-top: 50px;">
        <div class="col-md-5">
            <div class="card px-4 py-4" style="border-radius: 0;">
                <form @onsubmit="SubmitForm">
                    <div class="form-data">
                        <div class="mb-3">
                            <label for="identifiant" class="form-label">Identifiant</label>
                            <input style="background-color:#f0f6f7; border: 1px solid #f0f6f7;" type="text" class="form-control" @bind="@identifiant" placeholder="Identifiant">
                        </div>
                        <div class="mb-3">
                            <label for="mdp" class="form-label">Mot de passe</label>
                            <input style="background-color:#f0f6f7; border: 1px solid #f0f6f7;" type="password" class="form-control" @bind="@password" placeholder="Mot de passe" autocomplete="off">
                        </div>
                        <div class="mb-4 text-center">
                            <button type="submit" class="btn btn-dark mt-4">Connexion</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

@code {
    private string identifiant;
    private string password;

    private async Task SubmitForm()
    {
        AuthentificationRequest request = new AuthentificationRequest();
        request.Identifiant = identifiant;
        request.Password = password;
        request.Roles = new List<string> { "" };
        AuthentificationResponse resp = null;
        var response = await HttpClient.PostAsJsonAsync<AuthentificationRequest>("http://localhost:8001/api/Account/", request);
        if (response.IsSuccessStatusCode)
        {
            string result = response.Content.ReadAsStringAsync().Result;
            resp = JsonConvert.DeserializeObject<AuthentificationResponse>(result);
        }
        var httpContext = HttpContextAccessor.HttpContext;
        httpContext.Session.SetString("Identifiant", resp.Identifiant);
        httpContext.Session.SetString("JwtToken", resp.JwtToken);
        var jwt = new JwtSecurityTokenHandler().ReadJwtToken(resp.JwtToken);
        var claimsIdentity = new ClaimsIdentity(jwt.Claims, CookieAuthenticationDefaults.AuthenticationScheme);
        var authProperties = new AuthenticationProperties
            {
                ExpiresUtc = DateTime.UtcNow.AddMinutes((double)resp.ExpiresIn)
            };
        NavigationManager.NavigateTo("Index");
    }
}

页面引用代码

@page "/connexion"
@using Commons

@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor httpContextAccessor

<div>
    <component type="typeof(Login)" render-mode="ServerPrerendered" />
</div>

Program.cs配置

builder.Services.AddHttpClient();

排查与修复方案

1. 阻止表单默认提交行为

Blazor中表单的@onsubmit绑定方法如果未阻止默认提交,浏览器会触发页面刷新,中断异步请求,导致看不到网络记录。

  • 修复:修改SubmitForm方法,添加参数并阻止默认行为:
private async Task SubmitForm(EventArgs e)
{
    e.PreventDefault(); // 阻止浏览器默认表单提交
    // 原有逻辑...
}

2. 添加异常捕获逻辑

异步方法中未处理异常会导致静默失败,无任何提示。

  • 修复:在SubmitForm中添加异常捕获:
private async Task SubmitForm(EventArgs e)
{
    e.PreventDefault();
    try
    {
        // 原有逻辑...
    }
    catch (Exception ex)
    {
        Console.WriteLine($"登录错误:{ex.Message}");
        // 可添加页面错误提示
    }
}

3. 处理ServerPrerendered渲染模式的问题

ServerPrerendered预渲染阶段,HttpContextAccessor.HttpContext可能为null,直接访问会抛出空引用异常,中断代码执行。

  • 修复:
    • 改为Server渲染模式:
      <component type="typeof(Login)" render-mode="Server" />
      
    • 或在代码中增加null判断:
      var httpContext = HttpContextAccessor.HttpContext;
      if(httpContext != null && resp != null)
      {
          httpContext.Session.SetString("Identifiant", resp.Identifiant);
          httpContext.Session.SetString("JwtToken", resp.JwtToken);
          // 后续JWT处理逻辑...
      }
      

4. 配置Session服务

使用HttpContext.Session需要提前配置会话服务,否则会抛出异常。

  • 修复:在Program.cs中添加:
builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromMinutes(30);
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
});

// 在中间件管道中添加
app.UseSession();

5. 替换同步调用异步方法的写法

response.Content.ReadAsStringAsync().Result的同步调用可能导致死锁,中断请求。

  • 修复:改为异步等待:
string result = await response.Content.ReadAsStringAsync();

6. 处理API请求失败的场景

当API返回非成功状态码时,resp为null,后续访问resp的属性会抛出空引用异常,终止方法。

  • 修复:在使用resp前增加null判断:
if (response.IsSuccessStatusCode)
{
    string result = await response.Content.ReadAsStringAsync();
    resp = JsonConvert.DeserializeObject<AuthentificationResponse>(result);
}
else
{
    Console.WriteLine($"API请求失败:{response.StatusCode}");
    return; // 提前返回避免后续错误
}

if(resp == null)
{
    Console.WriteLine("未获取到有效认证响应");
    return;
}

// 后续Session处理逻辑...

内容的提问来源于stack exchange,提问作者Clément GRANDGIRARD

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 00:13:12