Only allow a certain role to see MiniProfiler results – MVC .NET

I am a big fan of MiniProfiler. It is perfect for development to see that you keep your code at best performance. However, wouldn’t it be nice to have the results available on your live server too? I thought so and here’s how to get it working in MVC .NET.

In your Global.asax.cs


protected void Application_BeginRequest()
{
    MiniProfiler.Start();
    MiniProfiler.Settings.IgnoredPaths = new[] { "static", "resources" };
}

protected void Application_PostAuthorizeRequest(object sender, EventArgs e)
{
    if (!UserHasProfilingAccess(Context))
    {
        MiniProfiler.Stop(discardResults: true);
    }
}

protected void Application_EndRequest()
{
   MiniProfiler.Stop();
}

private bool UserHasProfilingAccess(HttpContext context)
{
   return Request.IsLocal || context.User.IsInRole("Developer");
}