views:

55

answers:

4

I need to inject some text into an http response body generated by an ASP.NET MVC ViewResult. I've extended ViewResult and overridden the ExecuteResult Method, and at this point:

this.View.Render(viewContext, context.HttpContext.Response.Output);

I need to intercept the response output.

I know I can do something like:

var builder = new StringBuilder();
var writer = new StringWriter(builder);
this.View.Render(viewContext, writer);

// adjust builder

context.HttpContext.Response.Write(builder);

But I don't know what the best way to go about doing the injection is. How can I manipulate the reponse body string efficiently? I need to search for </body> (which will be close to the end of the string) and then insert some text.

Update The text i want to insert will be outputting to a TextWriter. Is there a way to avoid having to ToString() it?

Thanks

+1  A: 

What about StringBuilder.Replace?

One problem with this is that it's case sensitive.

CodeInChaos
A: 

Here is one method:

StringBuilder sb = new StringBuilder(theText);
int idx = theText.IndexOf("<body>");
sb.Insert(idx + "<body>".Length, textToInsert);
theText = sb.ToString();

This eliminates the problem of forgetting to have the "<body>" + textToInsert part (in replace), and cleans up code :)

Richard J. Ross III
i dont have the text as a string, its coming from a textwriter. I know i could .tostring() it, but this doesnt seem like the most efficient way
Andrew Bullock
Your code assumes he as the String available, but he old has the StringBuilder and StringWriter. Of course he could use sb.ToString() for the.InfexOf call.
CodeInChaos
A: 
string textToInsert = "Nick";
string searchstring = "<body></body>";
StringBuilder builder = new StringBuilder(searchstring);
builder.Insert(searchstring.IndexOf("<body>", 0, StringComparison.InvariantCultureIgnoreCase).Length, textToInsert);

That will output Nick

The problem is you always have to tostring stringbuilder. :(

Update: here is a way to optimize your query http://www.codeproject.com/KB/string/string_optimizations.aspx

Nicholas Mayne
+1  A: 

I don't know if this info is still up to date or not, but this article on codeproject looks like it has some great comparisons that you can run to find out what works best in your situation:

http://www.codeproject.com/KB/string/fastestcscaseinsstringrep.aspx

Derick Bailey