我只是通过ASP.NET Core构建用于流式视频的示例代码,并且我想支持“如何将字节数组写入Response.Body” 请帮帮我!
这是我的代码!
API
[HttpGet]
public IActionResult GetVideoContent()
{
return new PushStreamResult(OnStreamAvailabe, "video/mp4", HttpContext.RequestAborted);
}
PushStreamResult
//here we re using FileStream to read file from server//
using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 65536, FileOptions.Asynchronous | FileOptions.SequentialScan))
{
int totalSize = (int)fileStream.Length;
//here we are saying read bytes from file as long as total size of file
//is greater then 0
while (totalSize > 0)
{
int count = totalSize > bufferSize ? bufferSize : totalSize;
//here we are reading the buffer from orginal file
int sizeOfReadedBuffer = fileStream.Read(buffer, 0, count);
//here we are writing the readed buffer to output//
// ERROR HERE!
await outputStream.WriteAsync(buffer, 0, sizeOfReadedBuffer);
//and finally after writing to output stream decrementing it to total size of file.
totalSize -= sizeOfReadedBuffer;
}
//outputStream.Position = 0;
}
//这里出错!
等待outputStream.WriteAsync(buffer,0,sizeOfReadedBuffer);
PushStreamResult
public class PushStreamResult: IActionResult
{
private readonly Action<Stream, CancellationToken> _onStreamAvailabe;
private readonly string _contentType;
private readonly CancellationToken _requestAborted;
public PushStreamResult(Action<Stream, CancellationToken> onStreamAvailabe, string contentType, CancellationToken requestAborted)
{
_onStreamAvailabe = onStreamAvailabe;
_contentType = contentType;
_requestAborted = requestAborted;
}
public Task ExecuteResultAsync(ActionContext context)
{
var stream = context.HttpContext.Response.Body;
context.HttpContext.Response.GetTypedHeaders().ContentType = new MediaTypeHeaderValue(_contentType);
_onStreamAvailabe(stream, _requestAborted);
return Task.CompletedTask;
}
}