如何在返回IHttpActionResult的Web Api 2方法中从Byte []数组下载文件?

时间:2014-08-12 20:37:33

标签: download asp.net-web-api2

以下是我在ApiController课程中获得的方法。 _fileContents字典填充在另一个WebApi2方法BuildContent(params)中。 当用户对BuildContent(params)方法进行ajax调用时,该方法将构建 字典的字符串结尾,包含完整的HTML内容,包括表标记,并传回Guid,字典的结尾。 javascript依次执行以下操作:

window.location = 'api/MyController/DownloadFile/' + guid; 

ApiController static:

private static Dictionary<Guid, String> _fileContents = new Dictionary<Guid, String>();

ApiController方法:

public IHttpActionResult DownloadFile(Guid guid)
{
   try
    {
      if (_fileContents.ContainsKey(guid))
      {
         HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
         var content = Encoding.ASCII.GetBytes(_fileContents[guid]);
         using (var stream = new MemoryStream(content))
         {
            result.Content = new StreamContent(stream);
            result.Content.Headers.ContentType = 
                      new MediaTypeHeaderValue("application/octet-stream");
            result.Content.Headers.ContentDisposition = 
                           new ContentDispositionHeaderValue("attachment");
            result.Content.Headers.ContentDisposition.FileName = "MyFile.bin";
         }
       return Ok(result);
      }
      else
      {
        return NotFound();
      }
   }
   catch (Exception ex)
   {
     return InternalServerError(ex);
   }

    return BadRequest();
}

调用序列工作正常,但DownloadFile()方法抛出以下异常:

<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
The 'ObjectContent`1' type failed to serialize the response body for content type             'application/xml; charset=utf-8'.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace/>
<InnerException>
<Message>An error has occurred.</Message>
<ExceptionMessage>
Type 'System.Net.Http.StreamContent' cannot be serialized. Consider marking it with the     DataContractAttribute attribute, and marking all of its members you want serialized with     the DataMemberAttribute attribute. If the type is a collection, consider marking it with     the CollectionDataContractAttribute. See the Microsoft .NET Framework documentation for         other supported types.
</ExceptionMessage>
<ExceptionType>
System.Runtime.Serialization.InvalidDataContractException
</ExceptionType>

有人能告诉我发生了什么以及如何实现下载简单html文件的目标吗?

0 个答案:

没有答案