gpt4 book ai didi

azure - 如何将传出 HttpClient 请求正文记录到 Application Insights 依赖项表中?

转载 作者:行者123 更新时间:2023-12-02 05:56:17 26 4
gpt4 key购买 nike

我有一个 .Net core Web App API,它接受来自前端的请求,然后将 HTTP POST 请求发送到 Azure 搜索以获取搜索结果。

我只是使用内置应用程序洞察记录请求和依赖项源中的基本信息,并且具有零日志记录代码。

现在我想扩展默认的 Application Insights 依赖项表以将请求正文添加到 Azure 搜索。

用最少的代码最简单的方法是什么?

最佳答案

根据您的要求,您可以尝试以下代码:

public class RequestBodyInitializer : ITelemetryInitializer
{
readonly IHttpContextAccessor httpContextAccessor;

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

public void Initialize(ITelemetry telemetry)
{
if (telemetry is RequestTelemetry requestTelemetry)
{
if ((httpContextAccessor.HttpContext.Request.Method == HttpMethods.Post ||
httpContextAccessor.HttpContext.Request.Method == HttpMethods.Put) &&
httpContextAccessor.HttpContext.Request.Body.CanRead)
{
const string jsonBody = "JsonBody";

if (requestTelemetry.Properties.ContainsKey(jsonBody))
{
return;
}

//Allows re-usage of the stream
httpContextAccessor.HttpContext.Request.EnableRewind();

var stream = new StreamReader(httpContextAccessor.HttpContext.Request.Body);
var body = stream.ReadToEnd();

//Reset the stream so data is not lost
httpContextAccessor.HttpContext.Request.Body.Position = 0;
requestTelemetry.Properties.Add(jsonBody, body);
}
}
}

并将其添加到“启动”>“配置服务”

services.AddSingleton<ITelemetryInitializer, RequestBodyInitializer>();

关于azure - 如何将传出 HttpClient 请求正文记录到 Application Insights 依赖项表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70705622/

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