Tuesday, April 17, 2012

MiniProfiler for AJAX calls with ServiceStack.Net

I was surprised not to find this documented elsewhere on the Web.
ServiceStack.Net comes with a (slightly-modified) version of the MiniProfiler formerly-known-as "MVC MiniProfiler" now just referred to as "MiniProfiler" (http://miniprofiler.com) -- and it works great on their "HTML" service pages...but I wanted to get it to show on my MVC pages AND I also wanted it to update as I made JSON-formatted ajax calls to my web services.  So, here's what I did:

First, I'll here's my "_Layout.cshtml" file:
  1. You'll notice that I do RenderIncludes() before I include jquery. I had some problems doing it in the other order, all my AJAX calls were erroring.
  2. RenderIncludes() produces an HtmlEncoded string, so you end up with a bunch of < and stuff in your code, I'm wrapping it with @Html.Raw so that we get the actual raw text on the page.
That takes care of rendering the MiniProfiler for your MVC controller logic, but now we need to handle the ServiceStack.Net AJAX requests. Here's the javascript I used:

Basically, I'm grabbing the special Response header that ServiceStack adds called "X-MiniProfiler-Ids" that's a JSON-formatted array of ID numbers that correspond to MiniProfiler line-items -- then I'm telling the MiniProfiler to go get the data for those Ids.
That's it. After that, it "just works"

1 comment:

  1. Are your AJAX requests to the same domain as your site? I am trying to profile my AJAX requests to an API on a different domain and when I try to fetch the results as you mentioned I get a "Uncaught ReferenceError: MiniProfiler is not defined" error. Since the API has it's own MiniProfiler, I'm not even sure it's possible to show those results on my MVC site.

    ReplyDelete