从WebAPI调用返回Sitecore媒体项

时间:2017-03-22 13:35:43

标签: c# asp.net-web-api sitecore sitecore8

我有以下代码。我已经验证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;
}

1 个答案:

答案 0 :(得分:2)

我不认为使用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) };