我有一个日志文件,该文件正在由后台服务连续写入。到目前为止,用户需要能够下载文件。当我返回MVC FileResult
时,由于Content-Length不匹配,我收到了InvalidOperationException异常,大概是因为在提供文件时某些内容已写入文件中。有文件送达,通常可以,但是最后一行通常不完整。
后台服务实际上是在这样做:
var stream = new FileStream(evidenceFilePath, FileMode.Append, FileAccess.Write, FileShare.Read);
while (true) // obviously it isn't actually this, but it does happen a lot!
{
var content = "log content\r\n";
stream.Write(Encoding.UTF8.GetBytes(content);
}
以下是控制器操作的一些变体(所有结果都相同):
public IActionResult DownloadLog1()
{
return PhysicalFile("C:\\path\\to\\the\\file.txt", "text/plain", enableRangeProcessing: false); // also tried using true
}
public IActionResult DownloadLog2()
{
var stream = new FileStream("C:\\path\\to\\the\\file.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
return File(stream, "text/plain", enableRangeProcessing: false); // also tried true
}
这是我尝试以上任一方法时遇到的异常:
System.InvalidOperationException: Response Content-Length mismatch: too many bytes written (216072192 of 216059904). at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ThrowTooManyBytesWritten(Int32 count) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.VerifyAndUpdateWrite(Int32 count) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.WriteAsync(ReadOnlyMemory`1 data, CancellationToken cancellationToken) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpResponseStream.WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) at Microsoft.AspNetCore.Http.Extensions.StreamCopyOperation.CopyToAsync(Stream source, Stream destination, Nullable`1 count, Int32 bufferSize, CancellationToken cancel) at Microsoft.AspNetCore.Mvc.Infrastructure.FileResultExecutorBase.WriteFileAsync(HttpContext context, Stream fileStream, RangeItemHeaderValue range, Int64 rangeLength) at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeResultAsync(IActionResult result) at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResultFilterAsync[TFilter,TFilterAsync]() at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResultExecutedContext context) at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeResultFilters() at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter() at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context) at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync() at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync() at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext) at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext) at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext) at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)
我不太介意这个异常,但是如果没有发生,我更喜欢它。我确实需要修复不完整的最后一行问题。对我来说,最明显的解决方案是跟踪肯定已写入文件的字节数,并且以某种方式仅处理前n个字节。我看不到使用FileResult
以及构建它的各种帮助方法的简单方法。该文件可能会很大(最大可达500MB),因此在内存中进行缓冲似乎不切实际。
答案 0 :(得分:1)
我最终编写了一个自定义的ActionResult和IActionResultExecutor进行匹配,它们很大程度上基于MVC FileStreamResult和FileStreamResultExecutor:
2019-03-31
2019-05-31
2019-07-31
2019-08-31
2019-10-31
2019-12-31
2020-01-31
2020-03-31
2020-05-31
2020-07-31
我本来可以做更多的工作来添加其他构造函数重载来设置一些可选参数(例如下载文件名等),但这足以满足我的需求。
您需要在Startup.ConfigureServices中添加IActionResultExecutor:
public class PartialFileStreamResult : FileResult
{
Stream stream;
long bytes;
/// <summary>
/// Creates a new <see cref="PartialFileStreamResult"/> instance with
/// the provided <paramref name="fileStream"/> and the
/// provided <paramref name="contentType"/>, which will download the first <paramref name="bytes"/>.
/// </summary>
/// <param name="stream">The stream representing the file</param>
/// <param name="contentType">The Content-Type header for the response</param>
/// <param name="bytes">The number of bytes to send from the start of the file</param>
public PartialFileStreamResult(Stream stream, string contentType, long bytes)
: base(contentType)
{
this.stream = stream ?? throw new ArgumentNullException(nameof(stream));
if (bytes == 0)
{
throw new ArgumentOutOfRangeException(nameof(bytes), "Invalid file length");
}
this.bytes = bytes;
}
/// <summary>
/// Gets or sets the stream representing the file to download.
/// </summary>
public Stream Stream
{
get => stream;
set => stream = value ?? throw new ArgumentNullException(nameof(stream));
}
/// <summary>
/// Gets or sets the number of bytes to send from the start of the file.
/// </summary>
public long Bytes
{
get => bytes;
set
{
if (value == 0)
{
throw new ArgumentOutOfRangeException(nameof(bytes), "Invalid file length");
}
bytes = value;
}
}
/// <inheritdoc />
public override Task ExecuteResultAsync(ActionContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var executor = context.HttpContext.RequestServices.GetRequiredService<IActionResultExecutor<PartialFileStreamResult>>();
return executor.ExecuteAsync(context, this);
}
}
public class PartialFileStreamResultExecutor : FileResultExecutorBase, IActionResultExecutor<PartialFileStreamResult>
{
public PartialFileStreamResultExecutor(ILoggerFactory loggerFactory)
: base(CreateLogger<PartialFileStreamResultExecutor>(loggerFactory))
{
}
public async Task ExecuteAsync(ActionContext context, PartialFileStreamResult result)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (result == null)
{
throw new ArgumentNullException(nameof(result));
}
using (result.Stream)
{
long length = result.Bytes;
var (range, rangeLength, serveBody) = SetHeadersAndLog(context, result, length, result.EnableRangeProcessing);
if (!serveBody) return;
try
{
var outputStream = context.HttpContext.Response.Body;
if (range == null)
{
await StreamCopyOperation.CopyToAsync(result.Stream, outputStream, length, bufferSize: BufferSize, cancel: context.HttpContext.RequestAborted);
}
else
{
result.Stream.Seek(range.From.Value, SeekOrigin.Begin);
await StreamCopyOperation.CopyToAsync(result.Stream, outputStream, rangeLength, BufferSize, context.HttpContext.RequestAborted);
}
}
catch (OperationCanceledException)
{
// Don't throw this exception, it's most likely caused by the client disconnecting.
// However, if it was cancelled for any other reason we need to prevent empty responses.
context.HttpContext.Abort();
}
}
}
}
我的控制器动作因此变成:
services.AddTransient<IActionResultExecutor<PartialFileStreamResult>, PartialFileStreamResultExecutor>();
答案 1 :(得分:0)
文件是非托管资源。
因此,当您访问非托管资源(例如文件)时,将通过句柄打开它。如果是文件,则为open_file_handle(从内存中收集)。
因此,我建议(非常通用)建议写日志条目的最佳方法:
打开文件
写入文件
关闭文件,
处置(如果适用)
简而言之,不要让流保持打开状态。
第二,对于控制器,您可以查看MSDN示例以通过控制器提供文件。
答案 2 :(得分:0)
好吧,一般来说,您可能会遇到文件锁定问题,因此您需要进行计划和补偿。但是,您这里遇到的直接问题更容易解决。问题归结为返回流。该流是在返回响应时写入的,因此在创建响应正文时计算出的内容长度是错误的。
您需要做的是及时捕获日志,即将其读入byte[]
。然后,您可以返回它,而不是返回流,并且内容长度将正确计算,因为byte[]
在被读取后不会更改。
using (var stream = new FileStream("C:\\path\\to\\the\\file.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var ms = new MemoryStream())
{
await stream.CopyToAsync(ms);
return File(ms.ToArray(), "text/plain");
}