当前位置:  开发笔记 > 后端 > 正文

ASP.Net Core Web Api中的异步视频流无法正常工作

如何解决《ASP.NetCoreWebApi中的异步视频流无法正常工作》经验,为你挑选了1个好方法。

我之前使用过http://www.strathweb.com/2013/01/asynchronously-streaming-video-with-asp-net-web-api/这种技术,并且非常适合异步视频流.

但对于ASP.NET Core,这种方式并没有按预期工作.

通过视频流类是:

public class VideoStream
{
    private readonly string _filename;
    public VideoStream(string filename)
    {
        _filename = filename;
    }

    public async Task WriteToStream(Stream outputStream, HttpContent content, TransportContext context)
    {
        try
        {
            var buffer = new byte[65536];
            using (var video = File.Open(_filename, FileMode.Open, FileAccess.Read))
            {
                var length = (int)video.Length;
                var bytesRead = 1;
                while (length > 0 && bytesRead > 0)
                {
                    bytesRead = video.Read(buffer, 0, Math.Min(length, buffer.Length));
                    await outputStream.WriteAsync(buffer, 0, bytesRead);
                    length -= bytesRead;
                }
            }
        }
        catch (Exception)
        { return; }
        finally
        {
            outputStream.Flush();
            outputStream.Dispose();
        }
    }
}

我对视频流请求有以下操作:

    [HttpGet]
    [Route("[action]")]
    public IActionResult GetVideo(int id)
    {
        var fileName = GetVideoFileName(id);
        var video = new VideoStream(fileName);
        var response = new HttpResponseMessage
        {
            Content = new PushStreamContent(video.WriteToStream, new MediaTypeHeaderValue("video/mp4"))
        };
        var objectResult = new ObjectResult(response);
        objectResult.ContentTypes.Add(new Microsoft.Net.Http.Headers.MediaTypeHeaderValue("video/mp4"));
        return objectResult;
    }

由于默认情况下Asp.Net Core没有内置的Media Formatter for video/mp4我创建了以下自定义媒体格式化程序

 public class VideoOutputFormatter : IOutputFormatter
{
    public bool CanWriteResult(OutputFormatterCanWriteContext context)
    {
        if (context == null)
            throw new ArgumentNullException(nameof(context));
            return true;
    }
    public async Task WriteAsync(OutputFormatterWriteContext context)
    {
        if (context == null)
            throw new ArgumentNullException(nameof(context));
        var response = context.HttpContext.Response;
        response.ContentType = "video/mp4";

       How to impelemnt  ???
    }
}

并将以下行添加到Startup.cs

 services.AddMvc(options =>
        {
              options.OutputFormatters.Add(new VideoOutputFormatter());
        });

它实际上调用我的自定义格式化程序 我不知道如何为video/mp4实现这个自定义媒体格式化程序.有人可以帮帮我吗?



1> villecoder..:

查看Asp.NET Core的源代码确实可以帮助我找到答案。他们有一个StreamOutputFormatter类,它实际上与您要使用的类非常接近。我只需要修改它来寻找PushStreamContent它,它就像一个魅力。

这是我完整的VideoOutputFormatter:

public class VideoOutputFormatter : IOutputFormatter
{
    public bool CanWriteResult(OutputFormatterCanWriteContext context)
    {
        if (context == null)
            throw new ArgumentNullException(nameof(context));

        if (context.Object is PushStreamContent)
            return true;

        return false;
    }

    public async Task WriteAsync(OutputFormatterWriteContext context)
    {
        if (context == null)
            throw new ArgumentNullException(nameof(context));

        using (var stream = ((PushStreamContent)context.Object))
        {
            var response = context.HttpContext.Response;
            if (context.ContentType != null)
            {
                response.ContentType = context.ContentType.ToString();
            }

            await stream.CopyToAsync(response.Body);
        }
    }
}

而不是将包裹HttpResponseMessageObjectResult控制器中,您只需要将PushStreamContent对象推入ObjectResult。你仍然需要设置MediaTypeHeaderValueObjectResult

推荐阅读
农大军乐团_697
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有