2

In my APIController.cs Get() method, how can I return a IHttpActionResult with HTTP status code 200 and pass in a memory stream in the HTTP response?

I tried doing this:

    var sr = new StreamReader(myMemoryStream);
    string myStr = sr.ReadToEnd();
    return Ok(myStr);

But it converts my memory stream to string and pass that to Ok(). But I don't want to my memory stream to stream before sending in http respone. And I don't see any method in the OkResult object which allows me to set the response stream.

How can I set the http response body?

n179911
  • 19,547
  • 46
  • 120
  • 162

2 Answers2

0
public HttpResponseMessage GetFile()
{
  byte[] byteArray; 
  using (MemoryStream memoryStream = new MemoryStream())
  {
     // Do you processign here
     byteArray = memoryStream.ToArray();
  }
  var response = new HttpResponseMessage(HttpStatusCode.OK);
  response.Content = new ByteArrayContent(byteArray);
  response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
  response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
  //suppose its .xlsx file
  response.Content.Headers.ContentDisposition.FileName = "Sample.xlsx";
  return response;
}

if you are returning IHttpActionResult, then return

 return ResponseMessage(GetFile());

Please let me know if you want client side code also

Thakur
  • 559
  • 6
  • 15
-2

Try this code

 public IHttpActionResult GetStream()
 {
    MemoryStream myMemoryStream = new MemoryStream();
    var sr = new System.IO.StreamReader(myMemoryStream);
    string myStr = sr.ReadToEnd();
    return Ok(myStr);          
 }
Divyang Desai
  • 7,483
  • 13
  • 50
  • 76
Shimnas
  • 13
  • 4