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

 mobiledu2502898543 发布于 2023-02-06 10:46

在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;
}

而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;
}

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

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

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

谢谢-

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

    byte[] currentFile = ....
    

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

    return new FileContentResult(currentFile, "application/pdf");
    

    2023-02-06 10:49 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有