返回文件结果时出现HTTP错误500

时间:2018-09-18 20:49:18

标签: c# asp.net-web-api asp.net-core

我现在遇到一个非常奇怪的问题...我试图从我的Web API返回文件,但是即使流正在工作并且代码中没有抛出错误,但我仍收到HTTP错误500

var doc = DocX.Load(...);
// ...

var ms = new MemoryStream();
doc.SaveAs(ms);
doc.Dispose();

return File(ms, "application/octet-stream");

该流的大小为22kb,但是当我导航到api的URL时,我得到的是HTTP 500,为什么?

谢谢。

1 个答案:

答案 0 :(得分:4)

您忘记将内存流位置重置为开头。

var doc = DocX.Load(...);
// ...

var ms = new MemoryStream();
doc.SaveAs(ms);
doc.Dispose();
ms.Position = 0;

return File(ms, "application/octet-stream");

您还可以避免使用临时的MemoryStream

var doc = DocX.Load(...);
// ...

doc.SaveAs(Request.Body);
doc.Dispose();

return new EmptyResult();

或实施自定义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);
}