c# - Application insights 读取响应正文

标签 c# .net azure-application-insights

我正在使用 .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/

相关文章:

c# - Azure DevOps 测试数据库

c# - 异常和返回语句是 C# 中唯一可能的提前退出吗?

c# - Application Insights 日志自定义属性

c# - ApplicationInsights OperationId 为空

c# - MongoDB C# 驱动程序和线程安全

javascript - 将索引列添加到数据表

Windows Server 2012 中的 C# 动态 COM

c# - 将请求 header 添加到 Nancy 应用程序的 Application Insights 遥测

c# - 如何在 .NET Core 中重定向对程序集的探测?

c# - 使文本框接受一种语言