簡體   English   中英

如何返回帶有Http狀態碼200的IHttpActionResult並在http響應中傳遞內存流

[英]How to return a IHttpActionResult with Http status code 200 and pass in a memory stream in the http response

在我的APIController.cs Get()方法中,如何返回帶有HTTP狀態代碼200的IHttpActionResult並在HTTP響應中傳遞內存流?

我嘗試這樣做:

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

但是它將我的內存流轉換為字符串,並將其傳遞給Ok()。 但是我不希望在發送HTTP respone之前先流我的內存流。 而且我沒有在OkResult對象中看到任何允許我設置響應流的方法。

如何設置http響應正文?

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

如果返回IHttpActionResult,則返回

 return ResponseMessage(GetFile());

如果您還需要客戶端代碼,請告訴我

試試這個代碼

 public IHttpActionResult GetStream()
 {
    MemoryStream myMemoryStream = new MemoryStream();
    var sr = new System.IO.StreamReader(myMemoryStream);
    string myStr = sr.ReadToEnd();
    return Ok(myStr);          
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM