ASP.NET MVC5应用中Application Insights API使用最佳实践咨询
针对你在ASP.NET MVC5的Ajax控制器方法中使用Application Insights的场景,我整理了几个实用的最佳实践,帮你更高效地监控、排查问题:
1. 精准追踪异常,附带关键业务上下文
在异步方法的try-catch块中,不要只记录异常本身,要添加和业务强相关的自定义属性(比如DriverID、操作名称),这样在Application Insights里能快速定位到具体是哪个司机的同步操作出了问题。同时,要配合你现有的AjaxErrorHandling过滤器,实现全局+局部的异常追踪互补。
示例代码:
// 推荐通过依赖注入获取TelemetryClient,避免重复实例化 private readonly TelemetryClient _telemetryClient; public YourController(TelemetryClient telemetryClient) { _telemetryClient = telemetryClient; } [AjaxErrorHandling] [HttpPost] public async Task SyncDriverToVistracks(int DriverID) { if ([condition]) { // 业务逻辑前置操作 try { driver.VistrackId = await _vistracksService.AddNewDriverToVistracksAsync(driver); // 可选:追踪成功事件,便于统计同步成功量 _telemetryClient.TrackEvent("Driver_Sync_Success", new Dictionary<string, string> { {"DriverID", DriverID.ToString()}, {"VistrackID", driver.VistrackId.ToString()} }); } catch (Exception ex) { // 为异常添加业务上下文属性 var exceptionProps = new Dictionary<string, string> { {"Action", "SyncDriverToVistracks"}, {"DriverID", DriverID.ToString()}, {"RequestType", "Ajax"} }; _telemetryClient.TrackException(ex, exceptionProps); // 重新抛出异常,让AjaxErrorHandling过滤器继续处理响应逻辑 throw; } } }
2. 利用全局过滤器统一处理Ajax请求异常
你的AjaxErrorHandling过滤器是个很好的全局入口,可以在这里统一为所有Ajax请求的异常添加通用上下文(比如控制器名、当前用户),避免每个方法重复写相同的追踪逻辑:
public class AjaxErrorHandlingAttribute : FilterAttribute, IExceptionFilter { private readonly TelemetryClient _telemetryClient; // 同样推荐依赖注入TelemetryClient public AjaxErrorHandlingAttribute(TelemetryClient telemetryClient) { _telemetryClient = telemetryClient; } public void OnException(ExceptionContext filterContext) { if (filterContext.HttpContext.Request.IsAjaxRequest()) { var globalProps = new Dictionary<string, string> { {"Controller", filterContext.RouteData.Values["controller"].ToString()}, {"Action", filterContext.RouteData.Values["action"].ToString()}, {"CurrentUser", filterContext.HttpContext.User.Identity.Name ?? "Anonymous"} }; _telemetryClient.TrackException(filterContext.Exception, globalProps); // 原有Ajax错误响应逻辑保持不变 filterContext.Result = new JsonResult { Data = new { success = false, message = "同步操作失败,请稍后重试" }, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; filterContext.ExceptionHandled = true; } } }
3. 关联用户与会话上下文
如果你的应用有用户登录机制,记得把用户ID关联到Application Insights的遥测中,这样可以在AI的用户分析视图里,查看特定用户的操作记录和异常情况:
// 可以在控制器构造函数或Action方法中设置 _telemetryClient.Context.User.Id = User.Identity.Name; _telemetryClient.Context.Session.Id = HttpContext.Session.SessionID;
4. 追踪关键业务性能指标
如果SyncDriverToVistracks是耗时操作,可以添加性能追踪,记录方法的执行时间,帮助你识别性能瓶颈:
using (var operation = _telemetryClient.StartOperation<RequestTelemetry>("SyncDriverToVistracks_Ajax")) { operation.Telemetry.Properties["DriverID"] = DriverID.ToString(); try { // 执行核心业务逻辑 driver.VistrackId = await _vistracksService.AddNewDriverToVistracksAsync(driver); } catch (Exception ex) { operation.Telemetry.Success = false; _telemetryClient.TrackException(ex, operation.Telemetry.Properties); throw; } }
5. 避免重复实例化TelemetryClient
不要在每个方法里new TelemetryClient(),最好通过ASP.NET MVC的依赖注入容器(比如Unity、Autofac)注册并注入,这样Application Insights的配置(比如Instrumentation Key)会自动生效,也能保证遥测数据的一致性。
内容的提问来源于stack exchange,提问作者Oleg Sh
相关产品推荐
相关产品推荐

