应用洞察读取响应正文

ram*_*AIS 6 .net c# 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);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

要读取响应,我遇到了问题,即 context.Response.OutputStream 是只写的,我们无法直接读取它。在 core 中,我们有 response.body 属性,但在 .net 4.5 框架中没有。编写以下代码以登录无效的应用程序洞察。

using (var reader = new StreamReader(context.Response.OutputStream))
{
    string responseBody = reader.ReadToEnd();
    if (!telemetry.Context.Properties.ContainsKey("Response"))
    {
        requestTelemetry.Properties.Add("Response", responseBody);
    }
}
Run Code Online (Sandbox Code Playgroud)

请建议

Sam*_*ucy 0

您是正确的,您无法从 .Net 4.5 中的 HttpContext.Response 中读取。

我建议的替代方案是将要测量的数据写入 HttpContext.Items 字典,然后将其添加到遥测对象中。

因此,在构建预期响应的地方,您可以添加如下内容:

this.HttpContext.Items.Add("customProperty", "Information about the response");
Run Code Online (Sandbox Code Playgroud)

然后,您将更改尝试将响应数据添加到 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());
}
Run Code Online (Sandbox Code Playgroud)