在C#中的方法中返回FileStream是否安全?

kma*_*man 4 c# asp.net asp.net-web-api

在ASP.NET WebForms 4.5中,我使用WebAPI Controller和GET方法来获取PDF.

然后在应用程序的业务层中,我有一个API类,其中包含一个方法,该方法包含实际查找并将PDF返回给控制器的逻辑.

所以MyController类基本上有:

public HttpResponseMessage GetStatement(string acctNumber, string stmtDate) {
    MyApi myApi = new MyApi();
    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
    FileStream stream = myApi.GetStatement(acctNumber, stmtDate);
    ...set the response.Content = stream...
    ... set the mime type..
    ... close the stream...
    return response;
}
Run Code Online (Sandbox Code Playgroud)

而MyApi类有:

public FileStream GetStatement(string acctNumber, string stmtDate) {
    ... makes an HttpWebRequest to get a PDF from another system ...
    HttpWebRequest req = WebRequest.Create(......)....
    FileStream stream = new FileStream(accountNumber +"_" + stmtDate + ".pdf", FileMode.Create);
    response.GetResponseStream().CopyTo(stream);
    return stream;
}
Run Code Online (Sandbox Code Playgroud)

API类不在应用程序的Web层中,因为它由软件的其他(非Web)部分使用.

我想我担心的是API方法中没有明确关闭FileStream.我可以在Controller方法中做到这一点,但是当他们从其他区域调用它时,我会依赖其他人做同样的事情.

有没有更好的方法从API方法返回PDF文件?可能只是一个字节数组或类似的东西?优选尽可能少的开销.

谢谢-

Mar*_*rko 8

您不应该返回文件流,而是返回一个字节数组.这样您就可以正确地正确处理对象,而不用担心堆栈中的其他调用方法.

byte[] currentFile = ....
Run Code Online (Sandbox Code Playgroud)

然后,您可以按如下方式传送文件,字节数组很容易转换为任何内容.以下示例适用于MVC4.

return new FileContentResult(currentFile, "application/pdf");
Run Code Online (Sandbox Code Playgroud)

  • +1,因为这是一种合法的方法,但应该提到这需要您将整个文件一次性加载到内存中,如果允许用户以这种方式下载非常大的文件,则可能会导致性能大幅下降. (6认同)