作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 .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/
我是一名优秀的程序员,十分优秀!