Modify HTML response by native module with IIS 7 or above [Answered]RSS

1 reply

Last post Apr 18, 2018 09:59 AM by Bhavesh___

  • Modify HTML response by native module with IIS 7 or above

    Apr 16, 2018 07:12 AM|Bhavesh___|LINK

    Requirement:

    • Intercept all responses which serves "text/html" response.
    • Get the content of the html and modify it. E.g. "My ASP.Net Application" should be changed to "My Application".
    • This change should reflect in the page on browser.

    Details:

    1. Created a native module and using OnSendResponse to modify response.
    2. Call GetRawHttpResponse and loop through all chunks
    3. Find if the 'pChunk->FromMemory.pBuffer' contains required text. If present then replace with new text.
    4. Call AllocateRequestMemory with new size. Assign newly created string to 'pChunk->FromMemory.pBuffer' and also change 'pChunk->FromMemory.BufferLength'.

    Problem:  

    1. The above solution works when I hit the page first time. I can see the modified text on browser. If I refresh the page, it works fine sometimes. 
    2. If I navigate to another page in the same website, then the content of page is messed up. It contains some text out side the closing of HTML i.e. "</html>". Sometimes some text is inserted in the body.
    3. Some content from previous page are inserted while serving the current page.

    So I tried troubleshooting and commented the line which replaces text with new text. This happens even if I dont modify the content of the page and simply write the same content back i.e. modifying 'pChunk->FromMemory.pBuffer'

    Is there something wrong with the approach? I can provide code if required.

    I also tried using WriteEntityChunkByReference instead of directly modifying 'pChunk->FromMemory.pBuffer'. But it has same issue.

  • Re: Modify HTML response by native module with IIS 7 or above

    Apr 18, 2018 09:59 AM|Bhavesh___|LINK

    I got the solution. Pasting here is someone find it beneficial.

    This was my code to create local string from chunk:

    char * pStart = (char *)pChunk->FromMemory.pBuffer;

    std::string sChunk = (char*)pStart;

    The sChunk actually points to whole text pointed by pStart and it does not end at pChunk->FromMemory.BufferLength. My assumption was that it will truncate at pChunk->FromMemory.BufferLength.

    So use this instead and it works:

    std::string sChunk(pStart, pChunk->FromMemory.BufferLength);