gpt4 book ai didi

c# - 如何从不是从 Controller 派生的类返回 ActionResult(文件)?

转载 作者:行者123 更新时间:2023-12-01 19:14:42 24 4
gpt4 key购买 nike

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

如何从不是从 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);
}
}

错误是

An object reference is required for the non-static field, method, or property 'ControllerBase.File(Stream, string, string)'

对于这一行:

return (true, "", ControllerBase.File(bytes, "application/octet-stream", FriendlyName));

有可能实现这一目标吗?

最佳答案

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

new FileContentResult(fileContents, contentType) { FileDownloadName = fileDownloadName };

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

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

关于c# - 如何从不是从 Controller 派生的类返回 ActionResult(文件)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54647359/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com