Writing Memorystream to Response Object

Writing MemoryStream to Response Object

I had the same problem and the only solution that worked was:

Response.Clear();
Response.ContentType = "Application/msword";
Response.AddHeader("Content-Disposition", "attachment; filename=myfile.docx");
Response.BinaryWrite(myMemoryStream.ToArray());
// myMemoryStream.WriteTo(Response.OutputStream); //works too
Response.Flush();
Response.Close();
Response.End();

MemoryStream to HttpResponseMessage

I 'fixed' this by using base64 encoded string from the .Net controller to the javascript web api call result, and then allowed the browser to convert it into binary by specifying the type ('application/pdf').

Can WCF MemoryStream return type be written to the Http Response object for downloading as an Excel file?

You seem to retrun stream to request for partial page update with Update panel (search for Sys.WebForms.PageRequestManagerParserErrorException to find more details about exception).

Make sure that you are retruning stream only to full page request (GET/POST issued by browser itself, not by some script on the page that expects some particular type of responce).

Can we send a memory stream object with web API?

I found the solution like this:
here is in server side:

    [HttpGet("parameters")]
public IActionResult GetParameters()
{
var stream = _server.GetSerializedParameters();
stream.Seek(0, SeekOrigin.Begin);
return File(stream, MediaTypeNames.Text.Plain, "parameters.txt");
}

and here is in client-side:

        public MemoryStream StoreParameters()
{
var request =new HttpRequestMessage
{
RequestUri = new Uri("https://localhost:44316/api/parameters"),
Method = HttpMethod.Get
};
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var result = _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead).Result;
var ms = new MemoryStream();

result.Content.CopyToAsync(ms).Wait();
return result.IsSuccessStatusCode ? ms: null;
}

MemoryStream in response alongside other parameters possible?

You should be able to send any objects that can be read as JSON. Your CSV will eventually be converted to a string before the response gets send. Your backend will not stream the CSV but rather the response is send all at once.

You could try to serialize your object to a JSON string and return that string in the HttpResponse. Then you could read it in your frontend.

How to directly set response body to a file stream in ASP.NET Core middleware?

  1. No. You can never do that directly.

    Note that context.Response.Body is a reference to an object (HttpResponseStream) that is initialized before it becomes available in HttpContext. It is assumed that all bytes are written into this original Stream. If you change the Body to reference (point to) a new stream object by context.Response.Body = a_new_Stream, the original Stream is not changed at all.

    Also, if you look into the source code of ASP.NET Core, you'll find the Team always copy the wrapper stream to the original body stream at the end rather than with a simple replacement(unless they're unit-testing with a mocked stream). For example, the SPA Prerendering middleware source code:

        finally
    {
    context.Response.Body = originalResponseStream;
    ...

    And the ResponseCachingMiddleware source code:

        public async Task Invoke(HttpContext httpContext)
    {
    ...
    finally
    {
    UnshimResponseStream(context);
    }
    ...
    }

    internal static void UnshimResponseStream(ResponseCachingContext context)
    {
    // Unshim response stream
    context.HttpContext.Response.Body = context.OriginalResponseStream;

    // Remove IResponseCachingFeature
    RemoveResponseCachingFeature(context.HttpContext);
    }
  2. As a walkaround, you can copy the bytes to the raw stream as below:

    public async Task Invoke(HttpContext context)
    {
    context.Response.ContentType = "text/plain";
    using (var fs = new FileStream("valid-path-to-file-on-server.txt", FileMode.Open))
    {
    await fs.CopyToAsync(context.Response.Body);
    }
    }

    Or if you like to hijack the raw HttpResponseStream with your own stream wrapper:

        var originalBody = HttpContext.Response.Body;
    var ms = new MemoryStream();
    HttpContext.Response.Body = ms;
    try
    {
    await next();
    HttpContext.Response.Body = originalBody;
    ms.Seek(0, SeekOrigin.Begin);
    await ms.CopyToAsync(HttpContext.Response.Body);
    }
    finally
    {
    response.Body = originalBody;
    }


Related Topics



Leave a reply



Submit