Asp.net intercepts the html method generated by the server to be sent to the client

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.