gpt4 book ai didi

c# - 在 Controller 级别将自定义属性添加到遥测请求

转载 作者:行者123 更新时间:2023-12-03 04:14:04 25 4
gpt4 key购买 nike

我正在尝试为每条路线的遥测请求添加特定属性。经过一番挖掘,我发现我可以通过实现 ITelemetryInitializer 创建自己的自定义 TelemetryInitializer。通过这样做,我成功地将全局属性添加到请求中。但是,我仍然需要在 Controller 级别添加特定属性。您知道我该如何实现这一目标吗?

我尝试将 TelemetryClient 注入(inject) Controller ,但如果我使用它,属性将在请求之间共享。

这就是我尝试登录 Controller 的方式:

private TelemetryClient telemetryClient;

public ValueController(TelemetryClient telemetryClient)
{
this.telemetryClient = telemetryClient;
}

[HttpGet]
public async Task<IActionResult> RouteOne([FromQuery(Name = "param1")]string param1, [FromQuery(Name = "param2")]string param2)
{
telemetryClient.Context.GlobalProperties["param1"] = param1;
telemetryClient.Context.GlobalProperties["param2"] = param2;
}

[HttpGet]
public async Task<IActionResult> RouteTwo([FromQuery(Name = "param3")]string param3, [FromQuery(Name = "param4")]string param4)
{
telemetryClient.Context.GlobalProperties["param3"] = param3;
telemetryClient.Context.GlobalProperties["param4"] = param4;
}

这是 ITelemetryInitializer 的实现:

public class CustomPropertiesTelemetryInitializer : ITelemetryInitializer
{
private readonly IHttpContextAccessor httpContextAccessor;

public CustomPropertiesTelemetryInitializer(IHttpContextAccessor httpContextAccessor)
{
this.httpContextAccessor = httpContextAccessor;
}

public void Initialize(ITelemetry telemetry)
{
telemetry.Context.GlobalProperties["RequestId"] = httpContextAccessor.HttpContext.GetProperty("requestId");
telemetry.Context.GlobalProperties["Ip"] = httpContextAccessor.HttpContext?.Connection.RemoteIpAddress.ToString();
telemetry.Context.GlobalProperties["RoutePath"] = httpContextAccessor.HttpContext?.Request.Path;
}
}

最佳答案

如果您添加的属性总是类似于“paramxxx”,那么有一个解决方法(但它确实不是很优雅)。

在 Controller 构造函数中,检查 GlobalProperties 是否包含类似“paramxxx”的键:

public ValueController(TelemetryClient telemetryClient)
{
this.telemetryClient = telemetryClient;
var props = this.telemetryClient.Context.GlobalProperties;
foreach (var p in props)
{
if (p.Key.Contains("param"))
{
props.Remove(p.Key);
}
}
}

关于c# - 在 Controller 级别将自定义属性添加到遥测请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54774939/

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