Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Controller Using Response Stream

I'm using MVC 3 I would like to dynamically create a CSV file for download, but I am unsure as to the correct MVC orientated approach.

In conventional ASP.net, I would have written something like:

Response.ClearHeaders();
Response.ContentType = "text/csv";
Response.AddHeader("content-disposition", attachment;filename='Test.csv'");
Response.Write("1,2,3");
Response.End();

I have looked at the ContentResult action but it appears that I would need to create the result as a string, i.e.

return Content(myData, "text/csv");

I could, I suppose, build a string, but since these files could be several thousand lines long, this seems inefficient to me.

Could someone point me in the right direction? Thanks.

like image 546
Neilski Avatar asked Aug 23 '11 15:08

Neilski


1 Answers

I have found one possible solution to this problem. You can simply define the action method to return an EmptyResult() and write directly to the response stream. For example:

public ActionResult RobotsText() {
    Response.ContentType = "text/plain";
    Response.Write("User-agent: *\r\nAllow: /");
    return new EmptyResult();
}

This seems to work without any problems. Not sure how 'MVC' it is...

like image 79
Neilski Avatar answered Oct 06 '22 09:10

Neilski