.NET 6 Minimal API解析Form-Data文件时出现异常的问题
直接通过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

