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

p.campbell picture p.campbell · Oct 15, 2009 · Viewed 37.5k times · Source

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();
}

Answer

tvanfosson picture tvanfosson · Oct 15, 2009

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 ) );
}