Click here to Skip to main content
15,891,136 members
Articles / Web Development / ASP.NET

Using MVC Mini Profiler as an HTTP Module

Rate me:
Please Sign up or sign in to vote.
2.00/5 (1 vote)
2 Sep 2011CPOL 20.4K   5   1
MVC Mini Profiler is a great tool to profile your ASP.NET MVC apps.

MVC Mini Profiler is a great tool to profile your ASP.NET MVC apps. It’s easy to setup: all you need is to render some includes in your page’s HTML and start/stop the profiler on the BeginRequest/EndRequest event handlers, as desribed here.

However, I did not want to include that code and HTML includes in production pages, so I wrote an HTTP Module that you can switch on/off easily in your application’s web.config file. Here’s the code:

C#
public class MiniProfilerHttpModule: IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.BeginRequest += delegate
        {
            if (context.Request.IsLocal)
            {
                context.Response.Filter = 
                   new MiniProfilerFilterStream(context.Response.Filter);
                MiniProfiler.Start();
            }
        };

        context.EndRequest += delegate
        {
            MiniProfiler.Stop();
        };
    }

    public void Dispose()
    {
    }
}

That’s easy, the more interesting part is the MiniProfilerFilterStream class. It acts as a filter to all the response HTML that is returned to the browser. All it does is search for the end of the head tag and insert the output of the MvcMiniProfiler.MiniProfiler.RenderIncludes() method just before it. Here’s the source code of the class:

C#
public class MiniProfilerFilterStream: Stream
{
    private readonly Stream stream;
    private bool profilerHtmlRendered;

    public MiniProfilerFilterStream(Stream stream)
    {
        this.stream = stream;
    }

    public override void Flush()
    {
        stream.Flush();
    }

    public override long Seek(long offset, SeekOrigin origin)
    {
        return stream.Seek(offset, origin);
    }

    public override void SetLength(long value)
    {
        stream.SetLength(value);
    }

    public override int Read(byte[] buffer, int offset, int count)
    {
        return stream.Read(buffer, offset, count);
    }

    public override void Write(byte[] buffer, int offset, int count)
    {
        if (!profilerHtmlRendered)
        {
            var responseText = Encoding.UTF8.GetString(buffer, offset, count);

            if (responseText.Contains("</head>"))
            {
                var miniProfilerHtml = MiniProfiler.RenderIncludes().ToHtmlString();
                int index = responseText.IndexOf("</head>");
                var newOutput = responseText.Insert(index, miniProfilerHtml);
		var newBytes = Encoding.UTF8.GetBytes(newOutput);

                stream.Write(newBytes, 0, newBytes.Length);
                profilerHtmlRendered = true;
                return;
            }
        }

        stream.Write(buffer, offset, count);
    }

    public override bool CanRead
    {
        get { return stream.CanRead; }
    }

    public override bool CanSeek
    {
        get { return stream.CanSeek; }
    }

    public override bool CanWrite
    {
        get { return stream.CanWrite; }
    }

    public override long Length
    {
        get { return stream.Length; }
    }

    public override long Position
    {
        get { return stream.Position; }
        set { stream.Position = value; }
    }
}

The magic happens in the Write method, others just act as a proxy to the original stream.

Switching the MVC Mini Profiler on in your application is now as easy as adding the HTTP Module to the web.config:

XML
<system.web>
    <httpModules>
        <add name="MiniProfiler" 
           type="Management.Web.Infrastructure.Monitoring.MiniProfilerHttpModule"/>
    </httpModules>
</system.web>

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Lithuania Lithuania
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 2 Pin
AbdullaMohammad7-Dec-11 4:28
AbdullaMohammad7-Dec-11 4:28 
I would have preferred more explanation

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.