Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Web API 2 media controller that handles partial content requests
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