我目前有一个. NET 8 ASP.NET Core应用程序运行在我的PC上通过Kestrel和一个. NET for Android应用程序运行在我的物理设备上.

从移动应用程序,我试图上传一个大文件(~70 MB)到一个控制器使用流(更多信息,请参阅此:https://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-8.0#upload-large-files-with-streaming),并模拟一个丢失的连接(我模拟这通过禁用物理设备上的Wi—Fi).

问题是,由HttpContext.RequestAbortedexpose 的取消令牌没有被取消,使创建的文件锁定在文件系统上.代码如下:

await using var fileStream = IOFile.Create(filePath, bufferSize: 1024);

await fileSection.FileStream?.CopyToAsync(fileStream, HttpContext.RequestAborted);

注:只有在try 通过移动应用程序时才会出现此问题,当在同一台机器上执行Postman的相同测试时,ASP.NET Core应用程序正在运行取消令牌.

有没有人知道为什么 token 没有被取消?如果是:是否有解决办法?

先谢谢你.

推荐答案

i'm simulating this by disabling the wi-fi on the physical device)

This is not reliable client-side cancellation behavior.

What happens if the mobile client enters a no-network area while the file is being uploaded?

服务器定期发送keepalive探测器,以判断对等端是否仍在响应.如果对等体在预定时间内没有响应这些保活探测,系统会认为连接丢失.TCP保活间隔和重试次数通常是可配置的,但默认值可能导致在客户端失go 连接后数分钟到数小时内检测到断开连接.

Reliable solution

服务器应该在上传操作中添加超时机制,之后服务器将自动取消任务并处理上传的资源.

var cancellationTokenSource = new CancellationTokenSource();
// Set a timeout period, for example, 60 seconds
cancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(60));

try
{
    await using var fileStream = IOFile.Create(filePath, bufferSize: 1024);
    // A linked CancellationToken is used here, which is canceled when the RequestAborted or timeout
    var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationTokenSource.Token, HttpContext.RequestAborted);

    await fileSection.FileStream?.CopyToAsync(fileStream, linkedTokenSource.Token);
}
catch (OperationCanceledException)
{
    //  Handle cancellations, such as deleting or saving partially uploaded files
}

Csharp相关问答推荐

如何将ref T*重新解释为ref nint?

在Dapper中使用IasyncEum重写GetAsyncEum方法

如何使用C#中的图形API更新用户配置文件图像

如何在NServicebus中配置学习传输的文件夹(NService bus 8)

`Task`只有在C#中等待时才会运行吗?

在FilePath中搜索一个词,并根据First Match从左到右提取文件路径

(乌龙)1&#比c#中的UL&#慢吗?

Int和uint相乘得到LONG?

使用两个不同的枚举作为Switch语句中的CASE生成唯一值

Razor视图Razor页面指向同一端点时的优先级

C#普罗米修斯指标

为什么我可以用硬编码的集合而不是变量来设置没有setter的IList属性的值?

.NET:从XPath定位原始XML文档中的 node

HttpClient SendAsync与多线程环境中的ArchiveZip

在C#.NET项目中启动时,如何等待提升的PowerShell进程退出?

Celler ArgumentExpression是否期望在所有情况下都捕获允许空值的运算符?

在等待OnGetAsync时打开Razor Page显示微调器

EF Core 7-忽略模型绑定中的虚拟属性

我应该为C#12中的主构造函数参数创建私有属性吗?

Xamarin中出错.表单:应用程序的分部声明不能指定不同的基类