1

这是我在 MVC 应用程序中下载文件的代码。我有一个奇怪的错误,我无法纠正它。错误是 > 无法将类型“System.Web.Mvc.RedirectToRouteResult”隐式转换为“System.Web.Mvc.FileResult”

我想要这段代码是,虽然有一个文件下载它,但如果没有文件(null)那么它什么也不做或什么也不返回

 public FileResult Download(string Doc)
 {

    string fullPath = Path.Combine(Server.MapPath("~/UploadFiles/"), Doc);

    if (fullPath == null)
    {
        byte[] fileBytes = System.IO.File.ReadAllBytes(fullPath);

        return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, Doc);
    }

        return RedirectToAction("List");
         }
4

1 回答 1

1

将您的操作方法返回类型更改为ActionResult

两者RedirectResultFileResult继承自这个ActionResult抽象类。

你的 if 条件也没有意义!它将始终是falsePath.Combine 会给你一个非空字符串值。可能您想检查磁盘中是否存在文件?

public ActionResult Download(string Doc)
{    
    string fullPath = Path.Combine(Server.MapPath("~/UploadFiles/"), Doc);

    if (System.IO.File.Exists(fullPath))
    {
        byte[] fileBytes = System.IO.File.ReadAllBytes(fullPath);

        return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, Doc);
    }
    return RedirectToAction("List");
}

您的代码现在应该可以编译了。

于 2017-09-22T19:14:16.877 回答