Net Core 2 WebApi中的应用程序见解-共享上下文以附加属性

时间:2018-08-10 02:29:41

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

我们希望在Application Insights中记录附加到我们系统的每个授权请求中的用户名。

我遇到的问题是,以this article为指导,每当我尝试访问会话时都会抛出InvalidOperationException

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."

        }

    }
}

在WebApi系统中每个控制器的基类中,我们都从会话中获取用户详细信息-是否可以通过该方法获取当前请求上下文并将userId附加到该级别的Properties集合中请求的内容?

1 个答案:

答案 0 :(得分:3)

是的,您可以如下所示访问控制器内部的func storeTasks(tasksCodable:[Task]) -> Bool { if let encoded_in_data_format = try? JSONEncoder().encode(tasksCodable) { UserDefaults.standard.set(encoded_in_data_format, forKey: "tasks") return true } return false }

RequestTelemetry