ASP.NET MVC: return a plaintext file to load from the controller

Consider the need to return a text file from the controller method back to the caller. The idea is to download the file, rather than treat it as plain text in a browser.

I have the following method and it works as expected. The file is provided to the browser for download, and the file is populated with a line.

I would like to find a "more correct" implementation of this method, since I am not 100% comfortable with the void return type.

 public void ViewHL7(int id) { string someLongTextForDownload = "ABC123"; Response.Clear(); Response.ContentType = "text/plain"; Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.hl7", id.ToString())); Response.Write(someLongTextForDownload); Response.End(); } 
+52
asp.net-mvc download controller
Oct. 14 '09 at 23:18
source share
2 answers

Use the File method in the controller class to return a FileResult

 public ActionResult ViewHL7( int id ) { ... return File( Encoding.UTF8.GetBytes( someLongTextForDownLoad ), "text/plain", string.Format( "{0}.hl7", id ) ); } 
+110
Oct 14 '09 at 23:23
source share

You want to return FileContentResult from your method.

+5
Oct. 14 '09 at 23:21
source share



All Articles