Skip to content

Instantly share code, notes, and snippets.

@peaeater
Created May 8, 2020 19:09
Show Gist options
  • Save peaeater/872107097a3a9c9cdb851f3dc65fa61e to your computer and use it in GitHub Desktop.
Save peaeater/872107097a3a9c9cdb851f3dc65fa61e to your computer and use it in GitHub Desktop.
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