Search code examples
c#asp.net-web-apisitecoresitecore8

Returning Sitecore Media Item from WebAPI call


I have the following code. I have verified that the GetMediaItemByID is returning the expected media item, and the mime type is "application/pdf". However when I hit the controller that calls this code Acrobat complains that the resulting PDF file is invalid. I looked at the resulting PDF file in a text editor and it is binary data. Any ideas where I am going wrong?

public HttpResponseMessage RetrieveDocument(ID mediaID)
{
    MediaItem file = GetMediaItemByID(mediaID);

    Stream stream = file.GetMediaStream();
    MemoryStream ms = new MemoryStream();
    stream.CopyTo(ms);

    var result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(ms.GetBuffer()) };
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = file.Name + "." + file.Extension };
    result.Content.Headers.ContentType = new MediaTypeHeaderValue(file.MimeType);

    return result;
}

Solution

  • I don't think using ms.GetBuffer()) does what you expect it to do.

    Try this code instead:

    Stream mediaStream = mediaItem.GetMediaStream();
    var fileSize = mediaStream.Length;
    byte[] buffer = new byte[(int)fileSize];
    mediaStream.Read(buffer, 0, (int)mediaStream.Length);
    mediaStream.Close();
    
    var result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(buffer) };