日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

MiniProfiler,一个.NET简单但有效的微型分析器

發布時間:2023/12/4 asp.net 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 MiniProfiler,一个.NET简单但有效的微型分析器 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

背景

MVC MiniProfiler是Stack Overflow團隊設計的一款對ASP.NET MVC的性能分析的小程序。可以對一個頁面本身,及該頁面通過直接引用、Ajax、Iframe形式訪問的其它頁面進行監控,監控內容包括數據庫內容,并可以顯示數據庫訪問的SQL(支持EF、EF CodeFirst等 )。并且以很友好的方式展現在頁面上。

該Profiler的一個特別有用的功能是它與數據庫框架的集成。除了.NET原生的 DbConnection類,profiler還內置了對實體框架(Entity Framework)以及LINQ to SQL的支持。任何執行的Step都會包括當時查詢的次數和所花費的時間。為了檢測常見的錯誤,如N+1反模式,profiler將檢測僅有參數值存在差 異的多個查詢。

MiniProfiler是以Apache License V2.0協議發布的,你可以在NuGet找到。配置及使用可以看這里:http://code.google.com/p/mvc-mini-profiler

概述

在WebApi中,對其性能進行分析監測是很有必要的。而悲劇的是,MVC項目中可以使用的MiniProfiler或Glimpse等,這些都不支持WebApi項目,而且WebApi項目通常也沒有界面,不能進行性能分析的交互。在這篇文章中,我們就來一步步實現為WebApi項目集成Miniprofiler。集成后,我們可以監控EF執行效率,執行語句,頁面執行時間等,這些結果將以很友好的方式顯示在界面上。

問題

本質上,集成Miniprofiler可以分解為三個問題:

  • 怎樣監測一個WebApi項目的性能。

  • 將性能分析監測信息從后端發送到UI。

  • 在UI顯示分析監測結果。

  • 實現方式

    首先安裝Miniprofiler,MiniProfiler.EF6

    在Global.asax? 加入

    using BQoolCommon.Helpers.Model; using Elmah; using ResearchManager.Web.App_Start; using System; using System.Configuration; using System.Web; using System.Web.Mvc; using System.Web.Routing; using StackExchange.Profiling; using StackExchange.Profiling.Mvc; using StackExchange.Profiling.EntityFramework6; using System.Web.Optimization; using NLog; using ResearchManager.Models.ValidateAttribute;namespace ResearchManager.Web {public class MvcApplication : HttpApplication{protected void Application_Start(){AreaRegistration.RegisterAllAreas();FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);RouteConfig.RegisterRoutes(RouteTable.Routes);BundleConfig.RegisterBundles(BundleTable.Bundles);//Remove Header X-AspNetMvc-VersionMvcHandler.DisableMvcResponseHeader = true;AutofacConfig.Bootstrapper();//在 Controller 之前對 Model 做處理(字串 Trim)ModelBinders.Binders.DefaultBinder = new BQoolModelBinder();//註冊自訂的 Validation (複寫預設的錯誤訊息)CustomerValidation.RegisterCustomerValidation();DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CustomizedRequired), typeof(RequiredAttributeAdapter));DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CustomizedStringLength), typeof(StringLengthAttributeAdapter));#region 測試//if (bool.Parse(ConfigurationManager.AppSettings["MiniProfiler"] ?? "false"))//{MiniProfiler.Configure(new MiniProfilerOptions{RouteBasePath = "~/profiler",PopupRenderPosition = RenderPosition.Right, // defaults to leftPopupMaxTracesToShow = 10, // defaults to 15ResultsAuthorize = request => request.IsLocal,ResultsListAuthorize = request =>{return true; // all requests are legit in this example},// Stack trace settingsStackMaxLength = 256, // default is 120 charactersTrackConnectionOpenClose = true}.ExcludeType("SessionFactory") // Ignore any class with the name of SessionFactory).ExcludeAssembly("NHibernate") // Ignore any assembly named NHibernate.ExcludeMethod("Flush") // Ignore any method with the name of Flush.AddViewProfiling() // Add MVC view profiling (you want this));MiniProfilerEF6.Initialize();//}#endregion 測試}protected void Application_BeginRequest(Object source, EventArgs e){BundleTable.EnableOptimizations = false;#region 測試MiniProfiler.StartNew();#endregion 測試}protected void Application_EndRequest(){#region 測試//MiniProfiler.Current?.Stop(); // Be sure to stop the profiler!#endregion 測試}#region Elmahprivate static readonly string _exceptionMsg = "A potentially dangerous Request.Path value was detected from the client";protected void Application_Error(object sender, EventArgs e){Exception ex = Server.GetLastError();Logger nlogger = LogManager.GetCurrentClassLogger();nlogger.Error(ex);if (BQoolCommon.Helpers.Setting.CommonSetting.IsProd()){if (e is ExceptionFilterEventArgs exceptionFilter){if (exceptionFilter.Exception is HttpException httpException && httpException.Message.StartsWith(_exceptionMsg)){Response.Redirect("/");}}Response.Clear();Server.ClearError();Response.StatusCode = 404;}}/// <summary>/// 排除 Elmah 404 寄信通知/// </summary>public void ErrorMail_Filtering(object sender, ExceptionFilterEventArgs e){if (e.Exception is HttpException httpException && (httpException.GetHttpCode() == 404 || httpException.Message.StartsWith(_exceptionMsg))){e.Dismiss();}}/// <summary>/// 自定 Elmah 發信主旨/// </summary>private void ErrorMail_Mailing(object sender, Elmah.ErrorMailEventArgs e){string machineName = "none server";try{if (Request != null){machineName = Request.ServerVariables["HTTP_HOST"];}}catch{}// 取得 Elamh ErrorMail 的主旨// "$MachineName$ at $ErrorTime$ : {0}"string elmahSubject = e.Mail.Subject;//替換 ErrorMail 的主旨內容string emailSubject = string.Format("ResearchManager.Web Error => {0}",elmahSubject.Replace("$MachineName$", machineName));e.Mail.Subject = emailSubject;}#endregion Elmah} }

    運行效果

    運行項目,http://localhost//profiler/results-index? 即可看到監測結果

    總結

    以上是生活随笔為你收集整理的MiniProfiler,一个.NET简单但有效的微型分析器的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。