How can I modify the entire ASP.NET page content right before it's output?

Have you tried overriding the render method?

protected override void Render(HtmlTextWriter writer)
{
   StringBuilder htmlString = new StringBuilder(); // this will hold the string
   StringWriter stringWriter = new StringWriter(htmlString);
   HtmlTextWriter tmpWriter = new HtmlTextWriter(stringWriter);
   Page.Render(tmpWriter);
   writer.Flush();

   writer.Write(DoReplaceLogic(htmlString.ToString()););
}

There are two approaches you could use:

  1. This is similar to the accepted answer. But I would recommend overriding the render method in a BasePage and deriving all your templates from this.

  2. Use a HttpModule or the Global.asax and attach a Filter to the Response object. To me this make more aesthetic sense because the "Filter" property is supposed to help you filter the output which is exactly what you want!


Have you looked at the PreRender event in the life-cycle?

Before this event occurs:

• The Page object calls EnsureChildControls for each control and for the page.

• Each data bound control whose DataSourceID property is set calls its DataBind method.

• The PreRender event occurs for each control on the page. Use the event to make final changes to the contents of the page or its controls.

I believe this is the last place you could do something like this. The next event is SaveStateComplete, which according to the documentation has this behavior:

Before this event occurs, ViewState has been saved for the page and for all controls. Any changes to the page or controls at this point will be ignored. Use this event perform tasks that require view state to be saved, but that do not make any changes to controls.

Quote source: https://www.c-sharpcorner.com/UploadFile/8911c4/page-life-cycle-with-examples-in-Asp-Net/