Applicationinsights定制的遥测导致ObjectDisposedException

时间:2019-12-04 09:53:13

标签: c# asp.net .net azure-application-insights

我正在尝试为我们的应用程序见解服务获取已连接用户的用户名,但是将自定义遥测记录到用户名中会给我一个System.ObjectDisposedException occurred in mscorlib.dll but was not handled in user code错误。

例外:

Exception thrown: 'System.ObjectDisposedException' in mscorlib.dll
An exception of type 'System.ObjectDisposedException' occurred in mscorlib.dll but was not handled in user code
Safe handle has been closed

StackTrace:

System.ObjectDisposedException
  HResult=0x80131622
  Message=Safe handle has been closed
  Source=mscorlib
  StackTrace:
   at System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean& success)
   at System.StubHelpers.StubHelpers.SafeHandleAddRef(SafeHandle pHandle, Boolean& success)
   at Microsoft.Win32.Win32Native.GetTokenInformation(SafeAccessTokenHandle TokenHandle, UInt32 TokenInformationClass, SafeLocalAllocHandle TokenInformation, UInt32 TokenInformationLength, UInt32& ReturnLength)
   at System.Security.Principal.WindowsIdentity.GetTokenInformation(SafeAccessTokenHandle tokenHandle, TokenInformationClass tokenInformationClass)
   at System.Security.Principal.WindowsIdentity.get_User()
   at System.Security.Principal.WindowsIdentity.GetName()
   at System.Security.Principal.WindowsIdentity.get_Name()
   at Webeco.Infrastructure.Logging.AppInsightsInitializer.Initialize(ITelemetry telemetry) in C:\Users\SESEGU\Documents\Projects\WebEco\WebEco.Infrastructure\Logging\AppInsightsInitializer.cs:line 22
   at Microsoft.ApplicationInsights.TelemetryClient.Initialize(ITelemetry telemetry)

这是我正在使用的代码:

 public class TelemetryInitializer : ITelemetryInitializer
    {
        private readonly IHttpContextAccessor _httpContext;
        private readonly ILogger<TelemetryInitializer> _logger;

        public TelemetryInitializer(IHttpContextAccessor httpContext, ILogger<TelemetryInitializer> logger)
        {
            _httpContext = httpContext;
            _logger = logger;
        }

        public void Initialize(ITelemetry telemetry)
        {
            var requestTelemetry = telemetry as RequestTelemetry;
            if (requestTelemetry == null) return;
            if (!requestTelemetry.Context.GlobalProperties.ContainsKey("UserName"))
            {
                if (string.IsNullOrEmpty(_httpContext.HttpContext.User.Identity.Name))
                {
                    requestTelemetry.Context.GlobalProperties.Add("UserName", "NA");
                }
                else
                {
                    requestTelemetry.Context.GlobalProperties.Add("UserName", _httpContext.HttpContext.User.Identity.Name);
                }
            }
        }
    }

任何人都遇到类似的问题,您是如何解决的?

0 个答案:

没有答案