Web API 2 media controller that handles partial content requests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MediaApiController : ApiController | |
{ | |
public HttpResponseMessage Get(string filepath) | |
{ | |
var path = HostingEnvironment.MapPath($"~/media/{filepath}") ?? string.Empty; | |
var mediaType = MediaTypeHeaderValue.Parse(MimeMapping.GetMimeMapping(filepath)); | |
FileStream stream; | |
try | |
{ | |
stream = new FileStream(path, FileMode.Open, FileAccess.Read); | |
} | |
catch (FileNotFoundException) | |
{ | |
return Request.CreateResponse(HttpStatusCode.NotFound); | |
} | |
if (Request.Headers.Range != null) | |
{ | |
try | |
{ | |
var response = Request.CreateResponse(HttpStatusCode.PartialContent); | |
response.Content = new ByteRangeStreamContent(stream, Request.Headers.Range, mediaType); | |
response.Content.Headers.Expires = DateTimeOffset.Now.AddYears(10); | |
response.Headers.Add("Accept-Ranges", "bytes"); | |
response.Headers.CacheControl = CacheControlHeaderValue.Parse("public"); | |
return response; | |
} | |
catch (InvalidByteRangeException invalidByteRangeException) | |
{ | |
return Request.CreateErrorResponse(invalidByteRangeException); | |
} | |
} | |
else | |
{ | |
var response = Request.CreateResponse(HttpStatusCode.OK); | |
response.Content = new StreamContent(stream); | |
response.Content.Headers.ContentType = mediaType; | |
response.Content.Headers.Expires = DateTimeOffset.Now.AddYears(10); | |
response.Headers.Add("Accept-Ranges", "bytes"); | |
response.Headers.CacheControl = CacheControlHeaderValue.Parse("public"); | |
return response; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment