Blazor Server上传Excel至Minimal API时连接断开报错排查
Blazor大文件上传连接断开问题排查
问题现象
- 使用Telerik Blazor的
<TelerikFileSelect>组件选择Excel文件,以StreamContent形式发送至ASP.NET Core Minimal API端点 - 13KB小文件上传无异常,377KB文件上传时Blazor抛出错误:
Connection disconnected with error. Server returned an error on close: Connection closed with an error.
- 且目标API端点从未被请求命中
相关代码
Blazor端文件上传逻辑
async Task OnFileSelectHandler(FileSelectEventArgs args) { var uploadedFile = args.Files[0]; var content = new MultipartFormDataContent(); content.Add(new StreamContent(uploadedFile.Stream),"file", uploadedFile.Name); var response = await httpClient.PostAsync("processFile/", content); }
Minimal API端点定义
endpoints.MapPost("processFile", async (RboContext dbContext, LoggerService loggerService,IFormFile file ) => { // 业务逻辑 }
已配置但无效的Blazor端program.cs设置
builder.Services.AddServerSideBlazor() .AddHubOptions(options => { options.MaximumReceiveMessageSize = 100 * 1024 * 1024; options.ClientTimeoutInterval = TimeSpan.FromMinutes(2); options.KeepAliveInterval = TimeSpan.FromMinutes(2); options.EnableDetailedErrors = true; }); builder.Services.Configure<FormOptions>(options => { options.MultipartBodyLengthLimit = 100 * 1024 * 1024; }); builder.WebHost.ConfigureKestrel(options => { options.Limits.MaxRequestBodySize = 100 * 1024 * 1024; });
问题原因及修复方案
核心原因
你当前的配置仅修改了Blazor Server的Hub参数和Kestrel全局请求大小,但Minimal API端点可能存在独立的请求大小限制,同时Blazor端默认HttpClient也可能有未配置的大小/超时限制,这些都会导致大请求被提前截断,无法到达API端点。
具体修复步骤
给Minimal API端点单独配置请求大小限制
全局配置可能无法覆盖单个端点,需在端点定义时显式设置:endpoints.MapPost("processFile", async (RboContext dbContext, LoggerService loggerService,IFormFile file ) => { // 业务逻辑 }).DisableRequestSizeLimit(); // 或使用.RequestSizeLimit(100 * 1024 * 1024)指定具体大小配置Blazor端文件上传专用HttpClient
默认HttpClient存在请求大小和超时限制,需注册专用客户端:builder.Services.AddHttpClient("FileUploadClient", client => { client.Timeout = TimeSpan.FromMinutes(2); }).ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { MaxRequestContentBufferSize = 100 * 1024 * 1024; // 设置最大请求缓冲大小 });组件中注入并使用该客户端:
[Inject] IHttpClientFactory HttpClientFactory { get; set; } async Task OnFileSelectHandler(FileSelectEventArgs args) { var httpClient = HttpClientFactory.CreateClient("FileUploadClient"); var uploadedFile = args.Files[0]; // 重置流位置到起始处,避免读取异常 uploadedFile.Stream.Position = 0; var content = new MultipartFormDataContent(); content.Add(new StreamContent(uploadedFile.Stream),"file", uploadedFile.Name); var response = await httpClient.PostAsync("processFile/", content); }检查反向代理/服务器的请求限制
如果部署了IIS、Nginx等反向代理,需确认对应配置:- IIS:修改
web.config中的maxAllowedContentLength - Nginx:设置
client_max_body_size参数
这些外部限制会直接截断大请求,导致API端点无法接收。
- IIS:修改
内容的提问来源于stack exchange,提问作者Gouri
相关产品推荐
相关产品推荐

