I need to create filter that replace tags <h2>
in the HTML to <h3>
:
My filter
public class TagsFilter:Stream
{
HttpContext qwe;
public TagsFilter(HttpContext myContext)
{
qwe = myContext;
}
public override void Write(byte[] buffer, int offset, int count)
{
string html = System.Text.Encoding.UTF8.GetString(buffer);
html = html.Replace("<h2>", "<h3>");
qwe.Response.Write(html.ToCharArray(), 0, html.ToCharArray().Length);
}
My module
public class TagsChanger : IHttpModule
{
public void Init(HttpApplication context)
{
context.Response.Filter = new TagsFilter(context.Context);
}
I get error System.Web.HttpException:In this context, the answer is not available.
The problem is that you are applying the filter in the Init event, which only occurs once per application instance (it is essentially close to App_Start).
What you need to do is hook in the BeginRequest event from the Init event, and then apply the filter on BeginRequest.
I did a small example. I think you have to access the original stream, rather than accessing the httpContext.
Found the solution at this post on SO. Worked for me.
Look at Rick Strahl's post about "Capturing and Transforming ASP.NET Output with Response.Filter".
Rick Strahl wrote own implementation of stream filter that permits text replacing in right way.