Man*_*kas 2 c# asp.net-mvc file
是否可以File从方法返回对象controller?
目前所有的逻辑都是在控制器中完成的,所以我得到了这个:
public ActionResult Download(Guid id){
//some code to get file name, file stream and file content
return File(fileStream, file.ContentType, file.Name);
}
Run Code Online (Sandbox Code Playgroud)
但我想在控制器中得到的是:
//this is in the controller
public ActionResult Download(Guid id){
var file = GetFile(fileId);
return file;
}
Run Code Online (Sandbox Code Playgroud)
并且这个包含文件本身所有信息的方法应该在服务层:
//this is NOT in the controller
public File GetFile(Guid fileId){
//some logic to get all stuff
return File(fileStream, attachment.ContentType, attachment.Name);
}
Run Code Online (Sandbox Code Playgroud)
但是,我在这种情况下收到消息
“不可调用成员‘文件’不能像方法一样使用。”
我能做到这一点,还是应该忘记这一点并坚持我现在拥有的?
编辑:建议的问题没有回答我的问题!
我可以下载文件,但我希望在我的控制器中有一个返回File类型或其他内容的方法,并且这个方法应该在服务层的另一个项目中。所以这个方法应该以 object() 的形式返回文件,而不是流,而不是文件名或类型。而在控制器中,我只会调用此方法并仅返回此方法返回的内容。
GetFile 在服务层可以返回包含以下内容的自定义类型:
服务层中的类型:
public class CustomFile
{
public byte[] FileContents { get; set; }
public string ContentType { get; set; }
public string FileName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
和GetFile服务中的方法:
public CustomFile GetFile(Guid fileId)
{
// some logic to get all stuff
// set CustomFile here
// return CustomFile
}
Run Code Online (Sandbox Code Playgroud)
在控制器中(假设您已正确注入服务):
public ActionResult Download(Guid id)
{
var file = IYourService.GetFile(fileId);
return File(file.FileContents, file.ContentType, file.FileName);
}
Run Code Online (Sandbox Code Playgroud)
编辑:自定义类型可以替换为System.Web.Mvc.FileContentResult(虽然我不知道它是否可测试)。所以,GetFile看起来:
public FileContentResult GetFile(Guid fileId)
{
// some logic to get all stuff
// return new FileContentResult(FileContents, "MIMEType")
// {
// FileDownloadName = "FileName"
// };
}
Run Code Online (Sandbox Code Playgroud)
和控制器动作方法:
public FileContentResult Download(Guid id)
{
var file = IYourService.GetFile(fileId);
return file;
}
Run Code Online (Sandbox Code Playgroud)