从 WebAPI 调用返回 Sitecore 媒体项

Returning Sitecore Media Item from WebAPI call

我有以下代码。我已验证 GetMediaItemByID 正在返回预期的媒体项,并且 mime 类型是 "application/pdf"。但是,当我点击调用此代码的控制器时,Acrobat 抱怨生成的 PDF 文件无效。我在文本编辑器中查看了生成的 PDF 文件,它是二进制数据。我哪里出错了?

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;
}

我不认为使用 ms.GetBuffer()) 可以达到您期望的效果。

试试这个代码:

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) };