Подтвердить что ты не робот

Использование MVC Miniprofiler для каждого вызова действия

Iv экспериментировал с отличным инструментом, Mvc MiniProfiler.

Я не хочу замаскировать все мои представления множеством команд Step, поэтому я хочу использовать профилировщик при каждом вызове действий. Плохая идея? Это то, что я пробовал до сих пор:

 public abstract class BaseController : Controller
 {
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var profiler = MiniProfiler.Current;
            using (profiler.Step("Action: "+filterContext.ActionDescriptor.ActionName))
            {
                base.OnActionExecuting(filterContext);
            }
        }
}

Но я не думаю, что это делает то, что я намереваюсь? Думаю, мне нужно запустить профайлер на OnActionExecuting и остановить его на OnResultExecuted. Как это сделать, учитывая, что профилировщик предназначен для использования с инструкцией using.

4b9b3361

Ответ 1

Вы можете определить глобальный фильтр действий:

public class ProfileActionsAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var profiler = MiniProfiler.Current;
        var step = profiler.Step("Action: " + filterContext.ActionDescriptor.ActionName);
        filterContext.HttpContext.Items["step"] = step;
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var step = filterContext.HttpContext.Items["step"] as IDisposable;
        if (step != null)
        {
            step.Dispose();
        }
    }
}

и зарегистрируйтесь в Global.asax:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
    filters.Add(new ProfileActionsAttribute());
}

и это почти все.

Ответ 2

Хорошо думать и использовать ActionFilter. Но MVC все еще является приложением ASP.NET. Чтобы запустить и остановить MiniProfiler в начале и конце каждого запроса, вы можете попробовать события приложения в файле Global.asax.cs.

// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Global.asax.cs" company="Believe2014">
//   http://believeblog.azurewebsites.net/post/miniprofiler--log4net
// </copyright>
// <summary>
//   The mvc application.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

using System;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace Mvc4Application
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    /// <summary>
    ///     The mvc application.
    /// </summary>
    public class MvcApplication : HttpApplication
    {
        /// <summary>
        ///     The application_ start.
        /// </summary>
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();

            Profiler.Initialize();
        }

        /// <summary>
        /// The event when the application acquires request state.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The event argument..
        /// </param>
        protected void Application_AcquireRequestState(object sender, EventArgs e)
        {
            Profiler.Start(HttpContext.Current);
        }

        /// <summary>
        /// This function is called by ASP .NET at the end of every http request.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The event argument.
        /// </param>
        protected void Application_EndRequest(object sender, EventArgs e)
        {
            Profiler.Stop();
        }
    }
}