繁体   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