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

.NET 6 Minimal API解析Form-Data文件时出现异常的问题

.NET 6 Minimal API 中 Form-Data 上传PDF文件的偶发异常问题

直接通过HttpRequest读取上传文件时,偶尔触发异常,代码如下:

HttpRequest rq;
var uploads = rq.Form.Files ?? throw new BadRequestApiException();

对应的异常信息:

Microsoft.AspNetCore.Server.IIS.Core.IISHttpServer: Error: Unexpected exception in "IISHttpContext.ReadBody".

System.Threading.ThreadAbortException: System error.
at System.Diagnostics.Debugger.CustomNotification(ICustomDebuggerNotification data)
at System.Diagnostics.Debugger.NotifyOfCrossThreadDependencySlow()
at System.Runtime.CompilerServices.AsyncTaskMethodBuilder1.GetStateMachineBox[TStateMachine](TStateMachine& stateMachine, Task1& taskField)
at Microsoft.AspNetCore.Server.IIS.Core.IISHttpContext.ReadBody()
'iisexpress.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\6.0.3\Microsoft.Win32.Registry.dll'.

临时规避方法

如果先读取IFormFileCollection的第一个元素,再获取完整集合,就不会出现异常,且数据有效:

var temp = rq.Form.Files[0];
var uploads = rq.Form.Files ?? throw new BadRequestApiException();

自定义绑定方法的异常情况

为IFormFileCollection添加了基础的BindAsync解析方法,运行正常:

public static ValueTask<IFormFileCollection> BindAsyncIFormFileCollection(HttpContext context, ParameterInfo parameter)
 => new ValueTask<IFormFileCollection>(context.Request.Form.Files);

但扩展该方法增加Content-Type判断后,仍会偶尔出现相同异常:

public static ValueTask<IFormFileCollection> BindAsyncIFormFileCollection(HttpContext context, ParameterInfo parameter) {
return context.Request.Headers.TryGetValue("Content-Type", out var type)
        ? type.FirstOrDefault().Contains("multipart/form-data")
            ? new ValueTask<IFormFileCollection>(context.Request.Form?.Files)
            : throw new BadRequestApiException()
        : throw new BadRequestApiException();
}

恳请各位提供解决思路!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 04:40:43