ProfileAttribute for MvcMiniProfiler

I’ve been using the MvcMiniProfiler quite a bit lately.  I put it in production with Acturent and I’ve contributed a bit to the project.  With Acturent, I came up with a simple ActionFilterAttribute that I’m using to auto inject the profiler to all actions in the application.  Rather than going through and specifically adding @MvcMiniProfiler.MiniProfiler.RenderIncludes() to each view, I just slap the following attribute on my base controller class:

public class ProfileAttribute : ActionFilterAttribute{
  public override void OnResultExecuted(ResultExecutedContext filterContext) {
    base.OnResultExecuted(filterContext);
    if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest()) return;
    var session = ObjectFactory.Container.GetInstance<IUserSession>();
    if (session != null) {
      var user = session.GetCurrentUser();
      if (user == null || !user.IsAdmin) return;

      var includes = MiniProfiler.RenderIncludes().ToString();
      using (var writer = new StreamWriter(filterContext.HttpContext.Response.OutputStream)) {
        writer.Write(includes);
      }
    }
  }
}

Obviously it will need a bit of tweaking if you implement it in your app.  Specifically, the user validation code should be swapped out with whatever logic you want to use to determine who sees the profile information.

Leave a Reply

Your email address will not be published. Required fields are marked *