Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTP ERROR 500 when returning a File result [closed]

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.

like image 342
Haytam Avatar asked Mar 06 '23 09:03

Haytam


1 Answers

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);
}
like image 145
Kalten Avatar answered Apr 03 '23 20:04

Kalten