为了账号安全,请及时绑定邮箱和手机立即绑定

在 Application Insights 中查看请求的响应正文

在 Application Insights 中查看请求的响应正文

C#
拉莫斯之舞 2021-11-14 14:49:57
是否可以在 Application Insights 中查看请求的响应正文?我看过很多关于请求正文的问题/文章,但没有发现关于响应正文的指导。我正在构建一个 MVC 核心 2.1 Web Api。这是我的代码,从流创建读取器时出现异常,即“流不可读”。.public class ResponseBodyInitializer : ITelemetryInitializer{    readonly IHttpContextAccessor httpContextAccessor;    public ResponseBodyInitializer(IHttpContextAccessor httpContextAccessor)    {        this.httpContextAccessor = httpContextAccessor;    }    public void Initialize(ITelemetry telemetry)    {        if (telemetry is RequestTelemetry requestTelemetry)        {            HttpContext httpContext = httpContextAccessor.HttpContext;            HttpRequest request = httpContext.Request;            HttpResponse response = httpContext.Response;            if (request.Method == HttpMethods.Post ||                  request.Method == HttpMethods.Put)            {                //Log the response body                if (httpContext.Response.HasStarted)                {                    const string responseBody = "ResponseBody";                    if (requestTelemetry.Properties.ContainsKey(responseBody))                    {                        return;                    }                    try                    {                        var stream = new StreamReader(response.Body);                        var body = stream.ReadToEnd();                                                    response.Body.Position = 0;                        requestTelemetry.Properties.Add(responseBody, body);                    }                    catch (Exception ex)                    {                        throw ex;                    }                }            }        }    }}  
查看完整描述

3 回答

?
慕工程0101907

TA贡献1887条经验 获得超5个赞

你必须实施ITelemetryInitializer. 将 注入IHttpContextAccessor到类中并读取Initialize方法内的响应流。确保传递的ITelemetry对象来自类型RequestTelemetry并且 HttpRequest 是 Post 或 Put。然后,您可以使用该IHttpContext.HttpContext.Response.Body属性读取响应并使用 Application Insight 将其记录下来。

最后,在 Startup.cs 的 ConfigureService 方法中注册您的类


查看完整回答
反对 回复 2021-11-14
?
慕丝7291255

TA贡献1859条经验 获得超6个赞

我通过添加一个中间件来解决这个问题,该中间件将请求正文保存为HttpContext. app.UseMvc()由于 Mvc 框架处理流,因此之前注册中间件很重要。


启动文件


public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)

{

    app.Use(async (httpContext, next) =>

        {

            var request = httpContext.Request;


            if (request.Method == HttpMethods.Post || request.Method == HttpMethods.Put && request.Body.CanRead)

            {

                //Allows re-usage of the stream

                request.EnableBuffering();

                request.Body.Seek(0, SeekOrigin.Begin);


                using (var stream = new StreamReader(request.Body, Encoding.UTF8, true, 1024, true))

                {

                    var body = await stream.ReadToEndAsync();

                    //Reset the stream so data is not lost

                    request.Body.Position = 0;

                    var bodyFeature = new RequestBodyFeature(body); // RequestBodyFeature is a simple POCO

                    httpContext.Features.Set(bodyFeature);

                }


                request.Body.Seek(0, SeekOrigin.Begin);

            }


            await next.Invoke();

        });


        app.UseMvc();

}

当我从我的 ExceptionFilter 登录到 ApplicationInsights 时,我会得到这样的主体:


context.HttpContext?.Features.Get<RequestBodyFeature>()?.Body

我来到这个结论看完后这个问题的ApplicationInsights GitHub的页面上这个问题的AspNetCore GitHub的页面上。


查看完整回答
反对 回复 2021-11-14
?
三国纷争

TA贡献1804条经验 获得超7个赞

我解决了上面的问题,我在下面的博客中解释了解决方案。基本上它涉及使用消息处理程序将响应存储在请求消息中,并在实现 ITelemetryInitialize 的类中检索响应。

这是详细解释的博客。

https://thirum.wordpress.com/2019/08/19/logging-the-http-response-body-in-application-insights/


查看完整回答
反对 回复 2021-11-14
  • 3 回答
  • 0 关注
  • 204 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信