我正在使用 .net 4.5 框架。我能够读取使用 RequestTelemetry 登录应用程序见解的请求。编写了以下有效的代码。
var requestTelemetry = telemetry as RequestTelemetry;
if (requestTelemetry == null) return;
var context = HttpContext.Current;
if (context == null) return;
if (context.Request != null)
{
if ((context.Request.HttpMethod == HttpMethod.Post.ToString()
|| context.Request.HttpMethod == HttpMethod.Put.ToString()) && WhitelistCheck(context.Request.RawUrl))
{
using (var reader = new StreamReader(context.Request.InputStream))
{
string requestPayload = reader.ReadToEnd();
if (!telemetry.Context.Properties.ContainsKey(Request_Payload))
{
// TO DO: Don't log Personally identifiable information (PII)
requestTelemetry.Properties.Add(Request_Payload, requestPayload);
}
}
}
}
要读取响应,我遇到了问题,即 context.Response.OutputStream 是只写的,我们无法直接读取它。在 core 中,我们有 response.body 属性,但在 .net 4.5 框架中没有。 写下面的代码来记录我 n 不起作用的应用程序见解。
using (var reader = new StreamReader(context.Response.OutputStream))
{
string responseBody = reader.ReadToEnd();
if (!telemetry.Context.Properties.ContainsKey("Response"))
{
requestTelemetry.Properties.Add("Response", responseBody);
}
}
请推荐
最佳答案
您是正确的,您不能从 .Net 4.5 中的 HttpContext.Response 中读取。
我建议的替代方法是将您要测量的数据写入 HttpContext.Items 字典,然后将其添加到您的遥测对象。
因此,在构建预期响应的地方,您可以添加如下内容:
this.HttpContext.Items.Add("customProperty", "Information about the response");
然后您将更改您尝试将响应数据添加到 Application Insights 的代码。
if (context.Items["customProperty"] != null && !telemetry.Context.Properties.ContainsKey(Request_Payload))
{
// TO DO: Don't log Personally identifiable information (PII)
requestTelemetry.Properties.Add(Request_Payload, context.Items["customProperty"].ToString());
}
关于c# - Application insights 读取响应正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54624901/