In ASP.NET Core MVC, file results are action results designed to serve files to the client. They are particularly useful when you want your application to deliver files like PDFs, images, documents, or other binary content.
Types of File Results VirtualFileResult: Purpose: Serves a file from the application’s web root directory (wwwroot by default) or a virtual path. Parameters: virtualPath: The path to the file within the web root or the virtual path. contentType: The MIME type of the file (e.g., application/pdf). Usage: return new VirtualFileResult(“/sample.pdf”, “application/pdf”); return File(“/sample.pdf”, “application/pdf”); (Shorthand version) Benefits: Provides security by restricting file access to the web root or configured virtual paths.
PhysicalFileResult: Purpose: Serves a file from an absolute file path on the server’s file system. Parameters: physicalPath: The absolute path to the file. contentType: The MIME type of the file. Usage: return new PhysicalFileResult(@”c:\aspnetcore\sample.pdf”, “application/pdf”); return PhysicalFile(@”c:\aspnetcore\sample.pdf”, “application/pdf”); (Shorthand version) Benefits: Allows serving files from locations outside the web root, but requires careful handling due to potential security risks.
FileContentResult: Purpose: Serves a file from an in-memory byte array. Parameters: fileContents: The file contents as a byte array. contentType: The MIME type of the file. Usage: byte[] bytes = System.IO.File.ReadAllBytes(@”c:\aspnetcore\sample.pdf”); return new FileContentResult(bytes, “application/pdf”); return File(bytes, “application/pdf”); (Shorthand version) Benefits: Useful for dynamically generated files or when you don’t want to expose the file’s actual path.
Code // HomeController.cs [Route(“file-download”)] public VirtualFileResult FileDownload() { return File(“/sample.pdf”, “application/pdf”); // Serves from wwwroot }
[Route(“file-download2”)] public PhysicalFileResult FileDownload2() { return PhysicalFile(@”c:\aspnetcore\sample.pdf”, “application/pdf”); // Full path }