简体   繁体   中英

Application Insights in Net Core 2 WebApi - Share Context To Append Properties

We are looking to record the username attached to every authorized request for our system in Application Insights.

The issue I'm facing is, using this article as a guide, that it throws an InvalidOperationException whenever I try to access session.

public class PropertyTelemetryInitializer : ITelemetryInitializer
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public PropertyTelemetryInitializer(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public void Initialize(ITelemetry telemetry)
    {
        try
        {
            if (!(telemetry is RequestTelemetry requestTelemetry))
                return;

            if (_httpContextAccessor.HttpContext?.Session == null || !_httpContextAccessor.HttpContext.Session.IsAvailable)
                return;

            var userId = _httpContextAccessor.HttpContext.Session.GetInt32("UserId");
            requestTelemetry.Context.Properties["userId"] = userId?.ToString();
        }
        catch (Exception)
        {
            // Throws "Session has not been configured for this application or request."

        }

    }
}

We get the user details out of session in the base class of every controller in our WebApi system - is there a way to get the current request context at that point and append the userId to the Properties collection at that level of the request?

Yes, you can access the RequestTelemetry inside your controller as shown below.

    // GET api/values
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            var requestTelemetry = HttpContext.Features.Get<RequestTelemetry>();
            requestTelemetry.Context.Properties["userId"] = "myuserid"
            return new string[] { "value1", "value2" };
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM