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

.NET 8 Blazor:InputFile与原生input file异常处理行为差异咨询

.NET 8 Blazor全局交互式服务器渲染模式下InputFile与原生file输入的异常处理差异问题

在.NET 8 Blazor全局交互式服务器渲染模式中,我发现<InputFile>组件与原生<input type="file">的change事件处理器抛出异常时,处理行为存在明显差异。

我用Visual Studio 2022创建了Blazor Web应用测试项目,测试了以下4种事件绑定组合:

组合1:Async事件绑定的InputFile

<InputFile OnChange="async (e) => await InputFileChangedAsync(e)" />

@code {
    private async Task InputFileChangedAsync(InputFileChangeEventArgs e)
    {
        throw new Exception("InputFileChangedAsync");
    }
}

组合2:同步事件绑定的InputFile

<InputFile OnChange="InputFileChanged" />

@code {
    private void InputFileChanged(InputFileChangeEventArgs e)
    {
        throw new Exception("InputFileChanged");
    }
}

组合3:Async事件绑定的原生file输入

<input type="file" @onchange="async (e) => await InputChangedAsync(e)" />

@code {
    private async Task InputChangedAsync(ChangeEventArgs e)
    {
        throw new Exception("InputChangedAsync");
    }
}

组合4:同步事件绑定的原生file输入

<input type="file" @onchange="InputChanged" />

@code {
    private void InputChanged(ChangeEventArgs e)
    {
        throw new Exception("InputChanged");
    }
}

测试结果

  • <InputFile>抛出的异常仅显示在浏览器控制台,无法传递到ErrorBoundary,不符合预期;
  • 原生<input type="file">抛出的异常不会显示在浏览器控制台,但能正常传递到ErrorBoundary,符合预期。

复现步骤

  1. 创建新的Blazor Web应用,选择「全局交互式服务器」渲染模式;
  2. 在Routes.razor中用ErrorBoundary包裹Router:
<ErrorBoundary @ref="errorBoundary">
     <ChildContent>
         <Router AppAssembly="typeof(Program).Assembly">
             <Found Context="routeData">
                 <RouteView RouteData="routeData" DefaultLayout="typeof(Layout.MainLayout)" />
                 <FocusOnNavigate RouteData="routeData" Selector="h1" />
             </Found>
         </Router>
     </ChildContent>
     <ErrorContent Context="ctx">
         <p>Error</p>
         <p>@ctx.Message</p>
         <p>@ctx.ToString()</p>
     </ErrorContent>
</ErrorBoundary>

@code
{
     private ErrorBoundary errorBoundary;

     private void HandleError(Exception exception)
     {
         Console.WriteLine($"Error: {exception.Message}");
     }
}
  1. 编辑Counter.razor,添加上述4种输入组件及对应的抛异常事件处理器;
  2. 启动应用,分别使用每个输入组件选择文件触发事件。

请问我忽略了什么内容?感谢解答!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 06:30:09