我需要从我的 Controller 方法下载一个文件——可以是任何文件类型。我在 Stackoverflow 中找到的所有内容要么是从数据库下载的,要么是已知文件类型的。从到目前为止我找到的代码中,这是我的代码:
public FilePathResult ViewAttachment(string filePath, string fileName)
{
byte[] fileData = System.IO.File.ReadAllBytes(filePath);
string contentType = MimeMapping.GetMimeMapping(filePath);
return File(fileData, contentType, filePath);
}
不幸的是,这在返回文件行上给我一个错误:
Cannot explicitly convert type 'System.Web.Mvc.FileConentResult' to 'System.Web.Mvc.FilePathResult'
请您参考如下方法:
好吧,异常文本是不言自明的。
File 方法返回 FileContentResult 的实例,而不是 FilePathResult(并且 FileContentResult 不继承自 FilePathResult 所以显式转换是不可能的)。
应该是
public FileContentResult ViewAttachment(string filePath, string fileName)
甚至 ActionResult 作为所有 xxResult 类型继承自的最常见类型。
public ActionResult ViewAttachment(string filePath, string fileName)
