我有两种下载文件的方法,所以我想将实际击中磁盘的部分提取到一些帮助程序/服务类中,但是我很难将文件返回给控制器然后返回给用户
如何从不是从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);
}
}
错误是
非静态字段,方法或属性'ControllerBase.File(Stream,string,string)'需要对象引用
此行:
return (true, "", ControllerBase.File(bytes, "application/octet-stream", FriendlyName));
是否有可能实现这一目标?
答案 0 :(得分:3)
ControllerBase.File
只是为您创建FileContentResult
实例的一种便捷方法。这是使用的actual code:
new FileContentResult(fileContents, contentType) { FileDownloadName = fileDownloadName };
您可以简单地获取该代码并在您的班级中使用它,如下所示:
return (
true,
"",
new FileContentResult(bytes, "application/octet-stream") { FileDownloadName = FriendlyName });
答案 1 :(得分:1)
如果您看到ControllerBase
的功能,则可以复制:https://github.com/aspnet/AspNetCore/blob/c1bc210e8ebb6402ac74f4705d5748bc8e3ee544/src/Mvc/src/Microsoft.AspNetCore.Mvc.Core/ControllerBase.cs#L1120。
public virtual FileContentResult File(byte[] fileContents, string contentType, string fileDownloadName)
=> new FileContentResult(fileContents, contentType) { FileDownloadName = fileDownloadName };
因此,使用您的参数创建一个FileContentResult
并从操作中将其返回。