gpt4 book ai didi

c# - 将请求 header 添加到 Nancy 应用程序的 Application Insights 遥测

转载 作者:太空宇宙 更新时间:2023-11-03 20:57:19 24 4
gpt4 key购买 nike

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

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

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

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

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

最佳答案

实际上,.NET Framework 有一个示例:https://blogs.msdn.microsoft.com/stuartleeks/2016/11/03/including-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>();

同时检查: https://github.com/Microsoft/ApplicationInsights-aspnetcore/wiki/Custom-Configuration

关于c# - 将请求 header 添加到 Nancy 应用程序的 Application Insights 遥测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49135557/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com