【问题标题】:How to return ActionResult (file) from class that does not derive from Controller?如何从不是从 Controller 派生的类返回 ActionResult(文件)?
【发布时间】:2019-02-12 18:05:36
【问题描述】:

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

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

有没有可能做到这一点?

【问题讨论】:

    标签: c# asp.net-core asp.net-core-mvc


    【解决方案1】:

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

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

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

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

    【讨论】:

      【解决方案2】:

      如果你看到 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 并从操作中返回它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-02-22
        • 1970-01-01
        • 2021-08-29
        • 2015-06-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多