Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MiniProfiler.Current is null when called from System.Net.Http.DelegatingHandler

I'm using mini profiler in my asp.net Web API project and want to track the performance of some code that runs in a custom DelegatingHandler.

The calls MiniProfiler.Current.Step() inside the DelegatingHandler don't show up in the results. Other calls in the same project show up ok.

Further investigation revealed that MiniProfiler.Current is retrieved from HttpContext.Current in the WebRequestProfilerProvider. And HttpContext.Current is null when called from DelegatingHandler.

Is there a better way to retrieve the MiniProfiler.Current so that it works inside the handler?

like image 886
tozevv Avatar asked Jul 05 '13 11:07

tozevv


1 Answers

MiniProfiler Timings are stored in HttpContext.Current by default (as you discovered). Thus if you are calling MiniProfiler from a place where HttpContxt.Current is null, the results cannot be saved. The solution is to save (and retrieve) the results from somewhere else.

MiniProfiler offers the option of the option of changing the location where all results should be stored and retrieved from (using MiniProfiler.Settings.Storage). The new v3 MiniProfiler (beta nuget here) offers the option of configuring different IStorage for each request, and for using a MultiStorageProvider to designate multiple locations into which results can be stored and retrieved. You can see an example of this in the Sample.Mvc project on github.

In your case, the best approach might be to set a MultiStorageProvider for your global MiniProfiler.Settings.Storage that will first save/retrieve from HttpRuntimeCacheStorage and then afterwards will use some other IStorage that is accessible from the DelegatingHandler. Then in the DelegatingHandler, set the MiniProfiler.Current.Storage to only use the second storage option that you set in the MultiStorageProvider (since it is pointless to try to save the the HttpCache). In this was, profiles from the DelegatingHandler will be saved into your second storage option, and will be retrieved for view with your other results (since MultiStorageProvider will Load results from the first place it can get them - if it doesn't find the result in HttpCache, it will go to the second option.

Note - having multiple storage options is useful in this case, but it can have a negative impact on the performance of retrieving profiles.

like image 68
Yaakov Ellis Avatar answered Sep 19 '22 14:09

Yaakov Ellis