4

我正在使用 MVC 迷你探查器,我只为处于“探查器”角色的经过身份验证的用户显示探查器。MiniProfiler.cs 中的示例使用 AuthenticateRequest 方法来确定它是否应该停止分析,但我切换到使用 PostAuthorizeRequest (在阅读了这个问题之后),以便我可以访问 IPrincipal 和 IsInRole 方法。我可以只在 PostAuthorizeRequest 方法中启动探查器,还是应该继续停止并丢弃 PostAuthorizeRequest 中的结果?为每个请求启动和停止分析器的开销是多少?

当前代码:

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();
    };
}

建议代码:

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();
    };
}
4

2 回答 2

6

您可以随时使用以下调用放弃分析结果:

MiniProfiler.Stop(discardResults: true);

在 StackOverflow,我们的“高性能”模式是:

  1. 为所有经过授权的认证用户编写一个“秘密”cookie。
  2. 如果您在Application_BeginRequest- MiniProfiler.Start() 中找到 cookie;
  3. 之后PostAuthorizeRequest

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

您的目标始终是尽早开始分析,并尽可能晚地停止分析。如果您只从管道的中间开始,则不会分析可能存在瓶颈的管道部分。

于 2011-08-29T23:01:56.807 回答
1

我认为尽早启动分析器很重要(否则您可能会丢失一些关键信息,例如身份验证过程是否需要一段时间,或者某些 HTTP 模块是否存在问题)。

由于该BeginRequest事件发生在请求发生其他任何事情之前,这使其成为开始分析的理想场所,然后决定是否要在稍后的步骤中保留分析的数据(PostAuthorize在您的情况下)。

于 2011-08-29T19:04:51.413 回答