Problems with streaming video for IOS Client (Server developed on ASP.NET WEB API 2)
I just solved this one, and it was because the Content-Length
header had (what iOS considered to be) an invalid value.
My solution was based on method #2 above... Here's the important part of my code that actually worked.
if (!file.Exists) {
response.StatusCode = HttpStatusCode.NotFound;
response.ReasonPhrase = "Deleted";
} else {
var range = Request.Headers.Range?.Ranges?.FirstOrDefault();
if (range == null) {
using (var stream = new MemoryStream()) {
using (var video = file.OpenRead()) await video.CopyToAsync(stream);
response.Content = new ByteArrayContent(stream.ToArray());
}
response.Content.Headers.ContentType = new MediaTypeHeaderValue("video/mp4");
response.Content.Headers.ContentLength = file.Length;
} else {
var stream = new MemoryStream();
using (var video = file.OpenRead()) await video.CopyToAsync(stream);
response.Content = new ByteRangeStreamContent(
stream,
new RangeHeaderValue(range.From, range.To),
new MediaTypeHeaderValue("video/mp4")
);
// response.Content.Headers.ContentLength = file.Length;
// this is what makes iOS work
response.Content.Headers.ContentLength = (range.To.HasValue ? range.To.Value + 1 : file.Length) - (range.From ?? 0);
}
response.StatusCode = HttpStatusCode.OK;
}
I should probably put in an HTTP 206 (partial content) status when dealing with ranges, but I was working on this for nearly two days before coming up with a solution.
The only problem I have yet to fully track down is that from time-to-time, the Application_EndRequest
doesn't fire for some of these. I am able to log the response being sent by the endpoint, but it's like iOS disconnects the connection somewhere and the request hangs until it times out internally.