Request filter in HttpModule only works for form data

Jesper Lundin 1 Reputation point
2021-05-27T15:02:54.283+00:00

Hi,

Why does request filters in HttpModule only get triggered when the content type is x-www-form-urlencoded? A code example can be seen below.

Kind regards, Jesper

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace MyWebApplication
{
    public class MyHttpModule: IHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.BeginRequest += Application_BeginRequest;
        }

        private void Application_BeginRequest(Object source, EventArgs e)
        { 
            HttpApplication application = (HttpApplication) source;
            HttpContext context = application.Context;

            context.Request.Filter = new MyRequestFilter(context.Request.Filter, context.Request.ContentEncoding);
            var _ = context.Request.Form; // To trigger the evaluation of the inputstream
        }

        public void Dispose() { }
    }
}


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyWebApplication
{
    class MyRequestFilter: Stream
    {
        private MemoryStream ms;
        private Stream _stream;
        private Encoding _encoding;

        public RequestFilter(Stream stream, Encoding encoding)
        {
            _stream = stream;
            _encoding = encoding;
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            if (ms == null)
            {
                var sr = new StreamReader(_stream, _encoding);
                string content = sr.ReadToEnd();

                content = content.ToUpper();

                Byte[] bytes = _encoding.GetBytes(content);
                ms = new MemoryStream();
                ms.Write(bytes, 0, bytes.Length);
                ms.Seek(0, SeekOrigin.Begin);
            }

            return ms.Read(buffer, offset, count);
        }

        // rest of the overrides
        // ...
    }
}
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,482 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,921 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.