سؤال

I'm using the MVC Mini Profiler and I'm only showing the profiler for authenticated users who are in the "Profiler" role. The example shipping in MiniProfiler.cs was using the AuthenticateRequest method to determine if it should stop profiling, but I switched mine to use the PostAuthorizeRequest (after reading this question) so that I could get access to the IPrincipal and IsInRole method. Can I just start the profiler in the PostAuthorizeRequest method, or should I continue to Stop and discard the results in the PostAuthorizeRequest? What is the overhead to starting and stopping the profiler for every request?

Current Code:

public void Init(HttpApplication context)
{
    context.BeginRequest += (sender, e) =>
    {
        MiniProfiler.Start();
    };

    context.PostAuthorizeRequest += (sender, e) =>
    {
        var user = ((HttpApplication)sender).Context.User;

        if (user == null || !user.Identity.IsAuthenticated || !user.IsInRole("Profiler"))
        {
            MvcMiniProfiler.MiniProfiler.Stop(discardResults: true);
        }
    };

    context.EndRequest += (sender, e) =>
    {
        MiniProfiler.Stop();
    };
}

Proposed Code:

public void Init(HttpApplication context)
{
    context.PostAuthorizeRequest += (sender, e) =>
    {
        var user = ((HttpApplication)sender).Context.User;

        if (user != null && user.Identity.IsAuthenticated && user.IsInRole("Profiler"))
        {
            MiniProfiler.Start();
        }
    };

    context.EndRequest += (sender, e) =>
    {
        MiniProfiler.Stop();
    };
}
هل كانت مفيدة؟

المحلول

You can abandon your profiling results at any time using the call:

MiniProfiler.Stop(discardResults: true);

At StackOverflow our "high performance" pattern is:

  1. Write a "secretish" cookie for all authorized authenticated users.
  2. If you find the cookie in Application_BeginRequest - MiniProfiler.Start();
  3. After PostAuthorizeRequest:

if (MiniProfiler.Current != null && !userReallyAuthenticated) 
    MiniProfiler.Stop(discardResults: true);

Your goal is always to start profiling as early as possible, and stop profiling as late as possible. If you only start in the middle of the pipeline, portions of the pipeline where bottlenecks may reside will not be profiled.

نصائح أخرى

I think starting the profiler as early as possible is important (otherwise you could be missing some key information, such as if the authentication process it self takes a while, or if some HTTP module has issues).

Since the BeginRequest event occurs prior to anything else occurring with the request, this makes it the ideal place to begin profiling, then decide if you want to keep the profiled data at a later step (PostAuthorize, in your case).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top