Web API服务在读取流时挂起

use*_*152 6 .net c# asp.net asp.net-web-api asp.net-core-webapi

说明:我正在修改支持可恢复文件上载的ASP.NET Core Web API服务(托管在Windows服务中).这很好,并在许多故障条件下恢复文件上传,除了下面描述的一个.

问题:当服务在其他计算机上并且客户端在我的计算机上并且我拔掉计算机上的电缆时,客户端会在服务挂起在fileSection.FileStream.Read()时检测到网络不存在.有时服务会在8分钟内检测到故障,有时在20分钟内检测到故障

我还注意到,在拔掉电缆并停止客户端之后,服务停留在Read()函数并且文件大小为x KB,但是当服务最后一段时间检测到异常时,它会向文件写入额外的4 KB .这很奇怪,因为我关闭了缓冲,缓冲区大小为2 KB.

问题:如何正确检测服务上缺少网络,或正确超时,或取消请求

服务代码:

public static async Task<List<(Guid, string)>> StreamFileAsync(
   this HttpRequest request, DeviceId deviceId, FileTransferInfo transferInfo)
    {
        var boundary = GetBoundary(MediaTypeHeaderValue.Parse(request.ContentType), DefaultFormOptions.MultipartBoundaryLengthLimit);
        var reader = new MultipartReader(boundary, request.Body);
        var section = await reader.ReadNextSectionAsync(_cancellationToken);

        if (section != null)
        {
            var fileSection = section.AsFileSection();
            var targetPath = transferInfo.FileTempPath;

            try
            {
                using (var outfile = new FileStream(transferInfo.FileTempPath, FileMode.Append, FileAccess.Write, FileShare.None))
                {
                    var buffer = new byte[DefaultCopyBufferSize];
                    int read;

                    while ((read = fileSection.FileStream.Read(buffer, 0, buffer.Length)) > 0) // HANGS HERE
                    {
                        outfile.Write(buffer, 0, read);
                        transferInfo.BytesSaved = read + transferInfo.BytesSaved;
                    }
                }
            }
            catch (Exception e)
            {
                ...
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

客户端代码:

var request = CreateRequest(fileTransferId, boundary, header, footer, filePath, offset, headers, null);

using (Stream formDataStream = request.GetRequestStream())
    {
            formDataStream.ReadTimeout = 60000;

            formDataStream.Write(Encoding.UTF8.GetBytes(header), 0, header.Length);
            byte[] buffer = new byte[2048];

            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                fs.Seek(offset, SeekOrigin.Begin);

                for (int i = 0; i < fs.Length - offset;)
                {
                    int k = await fs.ReadAsync(buffer, 0, buffer.Length);
                    if (k > 0)
                    {
                        await Task.Delay(100);
                        await formDataStream.WriteAsync(buffer, 0, k);
                    }

                    i = i + k;
                }
            }

            formDataStream.Write(footer, 0, footer.Length);
        }

        var uploadingResult = request.GetResponse() as HttpWebResponse;



private static HttpWebRequest CreateRequest(
        Guid fileTransferId,
        string boundary,
        string header,
        byte[] footer,
        string filePath,
        long offset,
        NameValueCollection headers,
        Dictionary<string, string> postParameters)
    {
        var url = $"{_BaseAddress}v1/ResumableUpload?fileTransferId={fileTransferId}";
        HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
        request.Method = "POST";
        request.ContentType = "multipart/form-data; boundary=\"" + boundary + "\"";
        request.UserAgent = "Agent 1.0";
        request.Headers.Add(headers); // custom headers
        request.Timeout = 120000;
        request.KeepAlive = true;
        request.AllowReadStreamBuffering = false;
        request.ReadWriteTimeout = 120000;
        request.AllowWriteStreamBuffering = false;
        request.ContentLength = CalculateContentLength(filePath, offset, header, footer, postParameters, boundary);
        return request;
    }
Run Code Online (Sandbox Code Playgroud)

我尝试了什么:

  1. 我将这些添加到配置文件中:

  2. 试图在服务器上设置超时

    var host = new WebHostBuilder().UseKestrel(o => {o.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(2);})

  3. 使用async和非async Read()

  4. 试着保持活着而没有

  5. 尝试在网络恢复时中止请求:request?.Abort();

  6. 试图设置formDataStream.ReadTimeout = 60000;

use*_*152 0

由于我没有找到更好的方法,所以我决定为读取流添加超时并将其保存到文件中。很好的例子发布在这里: https: //blogs.msdn.microsoft.com/pfxteam/2012/10/05/how-do-i-cancel-non-cancelable-async-operations/

public static async Task<List<(Guid, string)>> StreamFileAsync(this HttpRequest request, DeviceId deviceId, FileTransferInfo transferInfo)
{
    var boundary = GetBoundary(MediaTypeHeaderValue.Parse(request.ContentType), DefaultFormOptions.MultipartBoundaryLengthLimit);
    var reader = new MultipartReader(boundary, request.Body);
    var section = await reader.ReadNextSectionAsync(_cancellationToken);

    if (section != null)
    {
        var fileSection = section.AsFileSection();
        var targetPath = transferInfo.FileTempPath;

        try
        {
            await SaveMyFile(...);
        }
        catch (OperationCanceledException){...}
        catch (Exception){...}
    }
}

private static async Task SaveMyFile(...)
{
        var cts = CancellationTokenSource.CreateLinkedTokenSource(myOtherCancellationToken);
        cts.CancelAfter(streamReadTimeoutInMs);
        var myReadTask = StreamFile(transferInfo, fileSection, cts.Token);
        await ExecuteMyTaskWithCancellation(myReadTask, cts.Token);
}


private static async Task<T> ExecuteMyTaskWithCancellation<T>(Task<T> task, CancellationToken cancellationToken)
{
        var tcs = new TaskCompletionSource<bool>();

        using (cancellationToken.Register(s => ((TaskCompletionSource<bool>) s).TrySetResult(true), tcs))
        {
            if (task != await Task.WhenAny(task, tcs.Task))
            {
                throw new OperationCanceledException(cancellationToken);
            }
        }

        return await task;
}

private static async Task<bool> StreamFile(...)
{
        using (var outfile = new FileStream(transferInfo.FileTempPath, FileMode.Append, FileAccess.Write, FileShare.None))
        {
            var buffer = new byte[DefaultCopyBufferSize];
            int read;

            while ((read = await fileSection.FileStream.ReadAsync(buffer, 0, buffer.Length, token)) > 0)
            {
                if (token.IsCancellationRequested)
                {
                    break;
                }

                await outfile.WriteAsync(buffer, 0, read);
                transferInfo.BytesSaved = read + transferInfo.BytesSaved;
            }

            return true;
        }
}
Run Code Online (Sandbox Code Playgroud)