How to properly authenticate mvc-mini-profiler with AspNetSqlMembershipProvider

后端 未结 3 824
心在旅途
心在旅途 2021-02-04 07:57

I tried to check if the user is in role at Application_BeginRequest and Application_AuthenticateRequest with this code and it will not work. At BeginRequest the code is never hi

相关标签:
3条回答
  • 2021-02-04 08:47

    This is my 2cent.

            context.AcquireRequestState += (sender, e) =>
            {
                // Check debug in session. Can be set from Querystring. (?debug=true)
                if (HttpContext.Current.Session != null && HttpContext.Current.Session["Debug"] != null)
                {
                    try{
                        bool debug = (bool)HttpContext.Current.Session["Debug"];
                        if (debug == true) 
                            MiniProfiler.Start();
                        else 
                            MiniProfiler.Stop(discardResults: true);
                    }
                    catch{ 
                        MiniProfiler.Stop(discardResults: true);
                    }
    
                }// Or always show if Administrator.
                else if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    bool admin = HttpContext.Current.User.IsInRole("Administrator");
                    if (admin == false)
                    {
                        MiniProfiler.Stop(discardResults: true);
                    }
                }
                else
                {
                    MiniProfiler.Stop(discardResults: true);
                }
            };
    
    0 讨论(0)
  • 2021-02-04 08:48

    The cookie feanz mentions is a handy trick, a second method is profiling unconditionally and then abandoning the session for an unauthenticated user:

    protected void Application_BeginRequest()
    {
       MvcMiniProfiler.MiniProfiler.Start();  
    }
    protected void Application_AuthenticateRequest(Object sender, EventArgs e)
    {
      if(!CurrentUserIsAllowedToSeeProfiler())
      {
        MvcMiniProfiler.MiniProfiler.Stop(discardResults: true);
      }
    }
    
    0 讨论(0)
  • 2021-02-04 08:56

    Begin request happens before the user is fully authenticated in the request life cycle.

    I solved this issue by adding a cookie if the user is in a role ("Admin" in your case) when the request is authenticated then you can check for this cookie on begin request and initialise the profiler.

    It wont't work the first time but should every time after that.

    0 讨论(0)
提交回复
热议问题