簡體   English   中英

如何在ASP.Net MVC中實現視頻文件流?

[英]How to implement video file streaming in ASP.Net MVC?

我想實現簡單的視頻文件流。 有我的API控制器:

[HttpGet]
[Route("api/VideoContent")]
public HttpResponseMessage GetVideoContent([FromUri] string fileName)
{
    if (fileName == null)
    {
        return new HttpResponseMessage(HttpStatusCode.BadRequest);
    }

    if (Request.Headers.Range != null)
    {
        try
        {
            //using (FileStream fileStream = _videoFileProvider.GetFileStream(fileName))
            //{
                HttpResponseMessage partialResponse = Request.CreateResponse(HttpStatusCode.PartialContent);
                FileStream fileStream = _videoFileProvider.GetFileStream(fileName);
                partialResponse.Content = new ByteRangeStreamContent(fileStream, Request.Headers.Range, new MediaTypeHeaderValue("video/mp4"));
                return partialResponse;
            //}

        }
        catch (Exception)
        {
            return new HttpResponseMessage(HttpStatusCode.InternalServerError);
        }
    }

    return new HttpResponseMessage(HttpStatusCode.RequestedRangeNotSatisfiable);
}

該代碼有效,但是如您所見,fileStream沒有被處理。 我嘗試使用using塊(帶注釋的行),但此代碼不起作用-在調試模式下無例外地運行方法,但瀏覽器顯示響應,並帶有500個錯誤代碼。

我的錯誤在哪里? 為什么我收到500 Internal Server Error? 我該如何正確處理文件流?

AFAIK,您在不處理文件流的情況下實現了下載內容的正確做法。

正如您一直使用HttpResponseMessage返回響應,該響應在將響應發送給客戶端之后由框架本身自動處理。

MSFT家伙已經在另一篇文章的 評論中指出了這一點

如果您在源代碼中查看HttpResponseMessage的處理方法,

        protected virtual void Dispose(bool disposing)
        {
            // The reason for this type to implement IDisposable is 
            //that it contains instances of types that implement
            // IDisposable (content). 
            if (disposing && !_disposed)
            {
                _disposed = true;
                if (_content != null)
                {
                    _content.Dispose();
                }
            }
        }

你可以看到_ content已被處置這類型的HttpContent你的情況,即,對象ByteRangeStreamContent在設置Content的屬性HttpResponseMessage

處置以下列方式實現的ByteRangeStreamContent對象:

        protected override void Dispose(bool disposing)
        {
            Contract.Assert(_byteRangeContent != null);
            if (disposing)
            {
                if (!_disposed)
                {
                    _byteRangeContent.Dispose();
                    _content.Dispose();
                    _disposed = true;
                }
            }
            base.Dispose(disposing);
        }

在上面的ByteRangeStreamContent Dispose方法中,您可以看到它正在處理自身並處理_ content (在您的情況下為FileStream ),后者是用於創建ByteRangeStreamContent對象的流。

我堅信,不處理文件流的實現是正確的,因為在完成向客戶端發送響應后按順序開始處理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM