I'm having a very weird problem right now... I am trying to return a file from my web api but i'm getting a HTTP ERROR 500 even though the stream is working and no errors are thrown in the code.
var doc = DocX.Load(...);
// ...
var ms = new MemoryStream();
doc.SaveAs(ms);
doc.Dispose();
return File(ms, "application/octet-stream");
The stream becomes of size 22kb but when I navigate to the api's url I get a HTTP 500, why?
Thank you.
You forgot to reset the memorystream position to the begining.
var doc = DocX.Load(...);
// ...
var ms = new MemoryStream();
doc.SaveAs(ms);
doc.Dispose();
ms.Position = 0;
return File(ms, "application/octet-stream");
You can also avoid the temporary MemoryStream
var doc = DocX.Load(...);
// ...
doc.SaveAs(Request.Body);
doc.Dispose();
return new EmptyResult();
Or implement a custom ActionResult
public class DocXResult : IActionResult
{
private DocX _doc;
public DocXResult(DocX doc) { _doc = doc); }
public Task ExecuteResultAsync(ActionContext context)
{
var response = context.HttpContext.Response;
response.ContentType = "application/octet-stream";
_doc.SaveAs(response.Body);
return Task.CompletedTask;
}
}
public IActionResult SendDocX()
{
DocX doc = null; // do your stuff
this.Response.RegisterForDispose(doc);
return new DocXResult(docX);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With