Is it possible to return File object from a method to controller?
Currently all logic is done in controller, so I got this:
public ActionResult Download(Guid id){
//some code to get file name, file stream and file content
return File(fileStream, file.ContentType, file.Name);
}
But what I would like to get have in controller is:
//this is in the controller
public ActionResult Download(Guid id){
var file = GetFile(fileId);
return file;
}
And this method with all information about file itself should be in service layer:
//this is NOT in the controller
public File GetFile(Guid fileId){
//some logic to get all stuff
return File(fileStream, attachment.ContentType, attachment.Name);
}
However, I this case get message
"Non-invocable member 'File' cannot be used like method."
Can I achieve this or should I forget that and stick with what I have now?
EDIT: Suggested question does not answers my question!
I can download file, but I want in my controller to have a method which returns File type or whatever, and this method should be in another project in service layer. So this method should return file as object(), not stream, not file name or type. And in controller I would only call this method and return only what this method returns.
GetFile in the service layer could return custom type that consists of:
The type in the service layer:
public class CustomFile
{
public byte[] FileContents { get; set; }
public string ContentType { get; set; }
public string FileName { get; set; }
}
And GetFile method in the service:
public CustomFile GetFile(Guid fileId)
{
// some logic to get all stuff
// set CustomFile here
// return CustomFile
}
And in the controller (assuming you have properly injected the service):
public ActionResult Download(Guid id)
{
var file = IYourService.GetFile(fileId);
return File(file.FileContents, file.ContentType, file.FileName);
}
Edit: Custom type could be replace by System.Web.Mvc.FileContentResult (I don't know whether it's testable though). So, GetFile looks:
public FileContentResult GetFile(Guid fileId)
{
// some logic to get all stuff
// return new FileContentResult(FileContents, "MIMEType")
// {
// FileDownloadName = "FileName"
// };
}
And the Controller action method:
public FileContentResult Download(Guid id)
{
var file = IYourService.GetFile(fileId);
return file;
}
Because File Class you are trying to use is part of System.IO and you need the controller.
https://msdn.microsoft.com/en-us/library/system.io.file(v=vs.110).aspx

where as what you have is

You could do the following, might be worth reviewing your code.
public FileContentResult GetFile(Guid fileId)
{
//some logic to get all stuff
return File(fileStream, attachment.ContentType, attachment.Name);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With