Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC: returning plaintext file to download from controller method

Consider the need to return a plain-text file from a controller method back to the caller. The idea is to have the file downloaded, rather than viewed as plaintext in the browser.

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

I'd like to look for a 'more correct' implementation of this method, as 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();
}
like image 236
p.campbell Avatar asked Oct 14 '09 23:10

p.campbell


2 Answers

Use the File method on 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 ) );
}
like image 170
tvanfosson Avatar answered Nov 16 '22 18:11

tvanfosson


You'll want to return a FileContentResult from your method.

like image 36
Chris Missal Avatar answered Nov 16 '22 18:11

Chris Missal