Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# MVC Instant Response to Browser?

Again, asking MVC noob questions. Forgive my lack of experience.

I have a situation where I am using an MVC route to return a large XML file. Sometimes it can be very large. Currently, I'm using a StringBuilder to build the XML output I want, and then returning it like this:

var sb = new StringBuilder();
XmlObject.WriteXml(sb);
return Content(sb.ToString(), "text/xml", Encoding.UTF8);

What I'm running into is that (for various reasons) the XML blog can take quite a long time to generate.

Within the XmlObject.WriteXml() method are calls to tons of other little methods that output bits and pieces of XML as they are called, so I START building an XML string right away, it just takes a while to finish. Each of these methods accepts a StringBuilder as an argument, so can created one and then pass it all over the place, using sb.Append() within each little method to build the final XML blob.

OK, so what I'd LIKE to do is start returning something to the client as soon as the string begins to build. In Webforms, I would have replaced all the StringBuilder paramaters with HttpResponse and used HttpResponse.Write() instead of StringBuilder.Append(), in a fashion similar to this:

this.Response.BufferOutput = false;
XmlObject.WriteXml(Response);

Then as each little piece of XML got written to the Reponse, the text would be sent to the client.

The problem I'm having is that the ActionResult has to have a return statement. I don't know how to treat in a similar fasion using an MVC route and ActionResult. Perhaps I need to be using something other than an ActionResult?

Thanks everybody!

like image 220
bopapa_1979 Avatar asked Feb 26 '23 21:02

bopapa_1979


1 Answers

You can change your action method to return void, then write directly to the response.
(That is possible; I've tried it)

like image 134
SLaks Avatar answered Mar 12 '23 20:03

SLaks