向 Nancy 应用程序的 Application Insights 遥测添加请求标头

Ori*_*ter 1 c# nancy telemetry azure-application-insights asp.net-core

我想在 Application Insights 中的请求事件中包含标头,并找到以下帖子,其中包含针对具有 HttpContext 的应用程序的解决方案。我正在使用 Nancy 应用程序,其中请求标头存储在 NancyContext 中。问题是 Nancy 没有提供像 HttpContext.Current 这样的静态访问器,所以我想知道如何解决它。

我做了两次尝试都没有成功。第一个是构建一个 ITelemetryInitializer,如下面的链接中所述,但随后我无法访问 NancyContext。

https://blogs.msdn.microsoft.com/stuartleeks/2016/11/03/include-headers-for-request-events-with-application-insights/

我的第二次尝试是将 NancyModule 传递给一个静态函数,该函数将请求标头添加到 ITelemetryContext,但随后我无法获得当前的 ITelemetryContext。

有没有其他人遇到并解决过这个问题?

Lie*_*ero 5

实际上,.NET Framework 有一个示例:https : //blogs.msdn.microsoft.com/stuartleeks/2016/11/03/include-headers-for-request-events-with-application-insights/

在 .NET Core 中,您只需使用 IHttpContextAccessor 而不是 HttpContext.Current 访问 HttpContext:

public class TelemetryHeadersInitializer : ITelemetryInitializer
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public List<string> RequestHeaders { get; set; }
    public List<string> ResponseHeaders { get; set; }

    public TelemetryHeadersInitializer(IHttpContextAccessor httpContextAccessor)
    {
        RequestHeaders = new List<string> { "Referer" }; //whatever you need
        ResponseHeaders = new List<string> { ... };
        _httpContextAccessor = httpContextAccessor;
    }

    public void Initialize(ITelemetry telemetry)
    {
        var requestTelemetry = telemetry as RequestTelemetry;
        // Is this a TrackRequest() ?
        if (requestTelemetry == null) return;

        var context = _httpContextAccessor.HttpContext;
        if (context == null) return;

        foreach (var headerName in RequestHeaders)
        {
            var headers = context.Request.Headers[headerName];
            if (headers.Any())
            {
                telemetry.Context.Properties.Add($"Request-{headerName}", string.Join(Environment.NewLine, headers));
            }             
        }
        foreach (var headerName in ResponseHeaders)
        {
            var headers = context.Response.Headers[headerName];
            if (headers.Any())
            {
                telemetry.Context.Properties.Add($"Response-{headerName}", string.Join(Environment.NewLine, headers));
            }
        }
    }
}

//Services.cs:
services.AddSingleton<ITelemetryInitializer, TelemetryHeadersInitializer>();
Run Code Online (Sandbox Code Playgroud)

另请检查:https : //github.com/Microsoft/ApplicationInsights-aspnetcore/wiki/Custom-Configuration