我正在尝试根据从服务总线触发器接收到的消息,通过调用的外部Web服务的验证错误来丰富我的依赖遥测。
我试图像这样在HttpContextAccessor
类中添加Startup
:
public class Startup : IWebJobsStartup
{
public void Configure(IWebJobsBuilder builder)
{
builder.Services.AddHttpClient();
builder.Services.AddHttpContextAccessor();
builder.Services.AddSingleton<ITelemetryInitializer, BadRequestReasonTelemetryInitializer();
}
}
然后像下面这样在我的遥测初始化程序中利用它:
public class BadRequestReasonTelemetryInitializer : ITelemetryInitializer
{
readonly IHttpContextAccessor _httpContextAccessor;
public BadRequestReasonTelemetryInitializer(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public void Initialize(ITelemetry telemetry)
{
if (telemetry is DependencyTelemetry req)
{
if (req.ResultCode == "400")
{
// toggle re-use
_httpContextAccessor.HttpContext.Request.EnableRewind();
var stream = new StreamReader(_httpContextAccessor.HttpContext.Request.Body);
var body = stream.ReadToEnd();
// reset stream to preserve data
_httpContextAccessor.HttpContext.Request.Body.Position = 0;
req.Properties.Add("Reason", body);
}
}
}
}
现在问题是HttpContext
始终为空。我认为这很有意义,因为我有一个带有ServiceBusTrigger
的函数。但是问题是如何从外部Web服务调用中获取当前的http上下文?是否有办法以某种方式从DependencyTelemetry
抢走它?我的目标是.NET Core 2.1和功能运行时v2。
编辑(为清晰起见,添加通话):
using (var httpClient = _httpClientFactory.CreateClient())
{
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken);
using (var result = await httpClient.PostAsync($"{BaseUrl}/endpoint", payload))
{
// if the result is 400 I would like this to go to AI through the initializer
}
}