【问题标题】:Application insights read response body应用程序洞察读取响应正文
【发布时间】:2019-02-11 06:18:23
【问题描述】:

我正在使用 .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);
    }
}

请推荐

【问题讨论】:

标签: c# .net azure-application-insights


【解决方案1】:

您是正确的,您无法从 .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());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 2022-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多