如何从不是从控制器派生的类返回 ActionResult(文件)?

Joe*_*lty 5 c# asp.net-core-mvc asp.net-core

我有两种下载文件方法,所以我想将实际命中磁盘的部分提取到某个帮助程序/服务类,但是我很难将该文件返回给控制器,然后返回给用户

如何从不是从Controller具有易于工作的方法的文件派生的类返回Mvc.ControllerBase.File

public (bool Success, string ErrorMessage, IActionResult File) TryDownloadFile(string FilePath, string FriendlyName)
{
    try
    {
        var bytes = File.ReadAllBytes(FilePath);

        if (FilePath.EndsWith(".pdf"))
        {
            return (true, "", new FileContentResult(bytes, "application/pdf"));
        }
        else
        {
            return (true, "", ControllerBase.File(bytes, "application/octet-stream", FriendlyName));
        }
    }
    catch (Exception ex)
    {
        return (false, ex.Message, null); 
    }
}
Run Code Online (Sandbox Code Playgroud)

错误是

非静态字段、方法或属性“ControllerBase.File(Stream, string, string)”需要对象引用

对于这一行:

return (true, "", ControllerBase.File(bytes, "application/octet-stream", FriendlyName));
Run Code Online (Sandbox Code Playgroud)

有没有可能实现这一目标?

Kir*_*kin 5

ControllerBase.File只是FileContentResult为您创建一个实例的便捷方法。这是实际使用的代码:

new FileContentResult(fileContents, contentType) { FileDownloadName = fileDownloadName };
Run Code Online (Sandbox Code Playgroud)

您可以简单地获取该代码并在您的类中使用它,如下所示:

return (
    true,
    "",
    new FileContentResult(bytes, "application/octet-stream") { FileDownloadName = FriendlyName });
Run Code Online (Sandbox Code Playgroud)