I wrote a custom IHttpModule but it is causing issues when there is no closing tag in the source. I have ran across a few pages in the CMS I am running this for where the .aspx page is used more like a handler and forgoes closing the html to give a response via ajax back to the user.
Here is my source:
public class HideModule : IHttpModule
{
public void Dispose()
{
//Empty
}
public void Init(HttpApplication app)
{
app.ReleaseRequestState += new EventHandler(InstallResponseFilter);
}
// ---------------------------------------------
private void InstallResponseFilter(object sender, EventArgs e)
{
HttpResponse response = HttpContext.Current.Response;
string filePath = HttpContext.Current.Request.FilePath;
string fileExtension = VirtualPathUtility.GetExtension(filePath);
if (response.ContentType == "text/html" && fileExtension.ToLower() == ".aspx")
response.Filter = new PageFilter开发者_Go百科(response.Filter);
}
}
public class PageFilter : Stream
{
Stream responseStream;
long position;
StringBuilder responseHtml;
public PageFilter (Stream inputStream)
{
responseStream = inputStream;
responseHtml = new StringBuilder ();
}
//Other overrides here
public override void Write(byte[] buffer, int offset, int count)
{
string strBuffer = System.Text.UTF8Encoding.UTF8.GetString (buffer, offset, count);
Regex eof = new Regex ("</html>", RegexOptions.IgnoreCase);
if (!eof.IsMatch (strBuffer))
{
responseHtml.Append (strBuffer);
}
else
{
responseHtml.Append (strBuffer);
string finalHtml = responseHtml.ToString();
//Do replace here
byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(finalHtml);
responseStream.Write(data, 0, data.Length);
}
}
#endregion
}
As you can see this is great because it only does the replace the last time Write is called, but if the output doesn't have a closing HTML tag, blammo.
My best option would be to not even add the new filter if a closing html is not found. But I don't think I can intercept the full stream that early. Failing that is there another way to detect Write is at the end of the stream besides looking for the closing html tag?
Thanks in advance.
Well, if it's WebForms, you should be able to do something like this in your InstallResponseFilter function:
if(Application.Context.CurrentHandler is System.Web.UI.Page
&& Application.Request["HTTP_X_MICROSOFTAJAX"] == null
&& Application.Request.Params["_TSM_CombinedScripts_"] == null)
{
response.Filter=new PageFilter(response.Filter);
}
精彩评论