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

登录发送验证码时触发NullReferenceException问题求助

解决Asp.NET Core SendCode POST请求中Providers为空的NullReferenceException问题

问题根源

SendCode视图渲染依赖model.Providers数据,但POST提交表单时,默认不会自动回传集合类型的属性,导致控制器POST方法接收的模型中Providers为null,最终视图执行时触发空引用异常。

解决方案

1. 在POST方法中重新填充Providers属性

在SendCode的POST方法内,重新获取Providers数据并赋值给模型,确保视图渲染时有可用数据:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SendCode(SendCodeViewModel model)
{
    if (!ModelState.IsValid)
    {
        // 重新获取Providers并赋值后返回视图
        model.Providers = await _signInManager.GetExternalAuthenticationSchemesAsync();
        return View(model);
    }

    // 后续业务逻辑代码...
}

2. 视图中添加空引用防护

在视图访问model.Providers前增加空判断,避免直接访问空对象:

@if (Model.Providers != null && Model.Providers.Any())
{
    @foreach (var provider in Model.Providers)
    {
        <!-- 渲染Provider相关内容 -->
        <div>@provider.DisplayName</div>
    }
}

3. 可选:通过隐藏字段回传Providers数据(如需在POST方法中使用)

如果需要在POST方法内使用Providers的具体数据,可在表单中添加隐藏字段序列化回传关键属性:

@model SendCodeViewModel

<form asp-action="SendCode">
    <!-- 其他表单元素 -->
    
    @for (int i = 0; i < Model.Providers.Count; i++)
    {
        <input type="hidden" asp-for="Providers[i].Name" />
        <input type="hidden" asp-for="Providers[i].DisplayName" />
    }
    
    <button type="submit">发送验证码</button>
</form>

额外检查项

  • 确认SendCodeViewModel的Providers属性为public访问级别,且类型匹配(如List<AuthenticationScheme>)。
  • 验证AntiForgeryToken配置是否正常,避免表单提交被拦截导致模型绑定失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 16:12:03