Sometimes we need to perform operations on the html generated by the server before sending the html generated by the server to the client, such as generating static html and saving and changing some content in the generated html, the following solutions can be used for a long time.
I have summarized two methods. I personally think it is better to use them. One is to rewrite the Page. Render () method. One is implemented through IHttpmodule.
1) This method is suitable for controlling a page. aspx. rewrite the Render () method in cs. This method provides an HtmlTextWriter type parameter, which contains the content to be sent to the client, according to the asp.net declaration cycle, we know that the Render phase is triggered after the load event. Therefore, this method is suitable for the desired effect. The following is a simple example:
Protected override void Render (HtmlTextWriter writer)
{
TextWriter tempWriter = new StringWriter ();
Base. Render (new HtmlTextWriter (tempWriter ));
String str = tempWriter. ToString (); // This str already contains html.
// You can then process the string, such as saving and replacing it.
Writer. Write (str); // send the modified html to the client.
}
2) This method is more suitable for application-level control. It is suitable for processing a certain type of page or comparing all pages. The PreSendRequestContent method of the interface to be registered. The following is an example of IHttpmodule content. This article does not repeat it:
Void context_PreSendRequestContent (object sender, EventArgs e)
{
HttpApplication app = (HttpApplication) sender;
HttpContext context = app. Context;
String url = context. Request. RawUrl;
StringWriter wr = new StringWriter ();
Context. Server. Execute (url, wr );
String htmlCon = wr. ToString (); // The htmlCon string contains the html to be sent to the client.
}
3) Replace Response. Filter.