【发布时间】:2015-07-27 03:24:54
【问题描述】:
我有一个 asp.net webforms 应用程序并从数据库中检索以varbinary 格式保存的视频并将其显示为 html5 视频标签。
在谷歌上搜索后,我找到了一种我应该使用ASP.Net WebApi 异步播放它的方法,它工作正常
第一个问题
当视频第一次播放并且用户点击播放按钮重新播放视频时,The remote host closed the connection. The error code is 0x800704CD 异常在await outputStream.WriteAsync(buffer, 0, bytesRead); 行抛出。
第二个问题
当用户点击搜索栏时,视频从第一个开始播放。
注意
Internet Explorer 11 播放视频没有任何问题,但 firefox 和 chrome 都有这两个问题。
我该如何解决这个问题?
这是我的代码:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.EnableCors();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "VideoApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
public class VideoController : ApiController
{
public IVideoRepository videoRepository;
public HttpResponseMessage Get(long id)
{
try
{
videoRepository = new VideoRepository();
Video video = videoRepository.load(id);
if (video != null)
{
var videoStream = new VideoStream(video.fileContent);
string ext = video.extension;
var response = Request.CreateResponse();
response.Content = new PushStreamContent((Action<Stream, HttpContent, TransportContext>)videoStream.WriteToStream, new MediaTypeHeaderValue("video/" + ext));
response.Content.Headers.Add("Content-Disposition", "attachment;filename=" + video.fullName.Replace(" ", ""));
response.Content.Headers.Add("Content-Length", videoStream.FileLength.ToString());
return response;
}
else
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
}
catch (Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.ServiceUnavailable, e);
}
}
}
public class VideoStream
{
private readonly byte[] _fileContent;
private long _contentLength;
public long FileLength
{
get { return _contentLength; }
}
public VideoStream(byte[] content)
{
_contentLength = content.Length;
_fileContent = content;
}
public async void WriteToStream(Stream outputStream, HttpContent content, TransportContext context)
{
try
{
var buffer = new byte[65536];
MemoryStream memoryStream = new MemoryStream();
memoryStream.Write(_fileContent, 0, _fileContent.Length);
memoryStream.Position = 0;
using (memoryStream)
{
var length = (int)memoryStream.Length;
var bytesRead = 1;
while (length > 0 && bytesRead > 0)
{
bytesRead = memoryStream.Read(buffer, 0, Math.Min(length, buffer.Length));
await outputStream.WriteAsync(buffer, 0, bytesRead);
length -= bytesRead;
}
}
}
catch (Exception e)
{
throw e;
}
finally
{
outputStream.Close();
}
}
}
更新
这种方式不能正常工作后,我不得不使用this way,但是新方式有seekbar问题,当用户点击seek bar来寻找时间时,它在Chrome和FireFox中不起作用。
【问题讨论】:
标签: asp.net asp.net-web-api webforms video-streaming html5-video