C# 如何从方法返回文件类型
是否可以将C# 如何从方法返回文件类型,c#,asp.net-mvc,file,C#,Asp.net Mvc,File,是否可以将文件对象从方法返回到控制器 目前所有逻辑都在控制器中完成,所以我得到了以下结果: public ActionResult Download(Guid id){ //some code to get file name, file stream and file content return File(fileStream, file.ContentType, file.Name); } 但我想在控制器中得到的是: //this is in the controller
文件
对象从方法返回到控制器
目前所有逻辑都在控制器中完成,所以我得到了以下结果:
public ActionResult Download(Guid id){
//some code to get file name, file stream and file content
return File(fileStream, file.ContentType, file.Name);
}
但我想在控制器中得到的是:
//this is in the controller
public ActionResult Download(Guid id){
var file = GetFile(fileId);
return file;
}
此方法以及有关文件本身的所有信息应位于服务层:
//this is NOT in the controller
public File GetFile(Guid fileId){
//some logic to get all stuff
return File(fileStream, attachment.ContentType, attachment.Name);
}
然而,我得到了这个消息
“不能像方法一样使用不可开票的成员‘File’。”
我能做到这一点吗?还是应该忘记这一点,坚持我现在所拥有的
编辑:建议的问题不能回答我的问题
我可以下载文件,但我想在我的控制器中有一个返回
file
type或其他任何类型的方法,这个方法应该在服务层的另一个项目中。所以这个方法应该以object()的形式返回文件,而不是流,不是文件名或类型。在控制器中,我只调用此方法并仅返回此方法返回的内容。GetFile
服务层中的可返回自定义类型,该类型包括:
- 字节[]
- 内容类型
- 文件名
public class CustomFile
{
public byte[] FileContents { get; set; }
public string ContentType { get; set; }
public string FileName { get; set; }
}
和服务中的GetFile
方法:
public CustomFile GetFile(Guid fileId)
{
// some logic to get all stuff
// set CustomFile here
// return CustomFile
}
public ActionResult Download(Guid id)
{
var file = IYourService.GetFile(fileId);
return File(file.FileContents, file.ContentType, file.FileName);
}
在控制器中(假设已正确注入服务):
编辑:自定义类型可以替换为System.Web.Mvc.FileContentResult
(但我不知道它是否可测试)。因此,GetFile
看起来:
public FileContentResult GetFile(Guid fileId)
{
// some logic to get all stuff
// return new FileContentResult(FileContents, "MIMEType")
// {
// FileDownloadName = "FileName"
// };
}
以及控制器动作方法:
public FileContentResult Download(Guid id)
{
var file = IYourService.GetFile(fileId);
return file;
}
因为您尝试使用的文件类是System.IO的一部分,您需要控制器 你现在在哪里 您可以执行以下操作,可能值得检查您的代码
public FileContentResult GetFile(Guid fileId)
{
//some logic to get all stuff
return File(fileStream, attachment.ContentType, attachment.Name);
}
也许你只需要一个新的?可能重复的@Ian是的,System.IO.File是…。@PeterA.Schneider啊,我注意到了。这是
MVC
file…file
是一个静态类,不允许使用new
这是一种比现在更紧凑的方式。但是有可能从GetFile
方法返回File
类型而不是CustomFile
类型吗?我认为GetFile
可以返回System.Web.Mvc.FileContentResult
,它包含了您需要的所有内容,为变量添加了逻辑,并且已经完成了!谢谢