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

asp.net MvcControllerDownload

asp.net Mvc Problem Overview


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

asp.net Mvc Solutions


Solution 1 - asp.net Mvc

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

Solution 2 - asp.net Mvc

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionp.campbellView Question on Stackoverflow
Solution 1 - asp.net MvctvanfossonView Answer on Stackoverflow
Solution 2 - asp.net MvcChris MissalView Answer on Stackoverflow