c# - 遥测初始化程序从 .net core MVC 应用程序添加请求正文内容以请求遥测属性不起作用

标签 c# asp.net-core azure-application-insights

我正在尝试将应用程序见解集成到.net core MVC 应用程序中。一切都按预期工作,直到我添加了遥测初始化程序来读取请求正文内容。我创建了一个 ITelemetryInitializer,如果遥测类型是请求遥测,它会从请求正文中读取内容。但我收到“System.ObjectDisposeException:'无法访问已处置的对象。'”

问题:

在调试时我注意到,当进行 POST/PUT http 调用时,MVC 操作方法会在 Initialize() 方法之前调用。因此,当调用 Initialize() 方法时,请求正文请求流已被释放。我对 4.6 框架 Web api 应用程序有类似的实现,但它工作正常,没有这个问题。

有没有办法可以在执行 MVC 操作之前调用初始化程序。我尝试使用 IWebHostBuilder 和 IServiceCollection 配置应用程序见解。

有人遇到过这个问题吗?

版本信息 SDK版本:2.2.1 .NET版本:.Net核心2.0 如何使用 SDK(VisualStudio/StatusMonitor/Azure 扩展)加载应用程序: 操作系统: 托管信息(IIS/Azure WebApps/等):IIS

更新(从评论中复制代码):

if (!(telemetry is RequestTelemetry requestTelemetry))
   return;
var request = _httpContextAccessor.HttpContext?.Request;
if (request == null)
   return;
if (request.Body.CanRead)
{
   request.EnableRewind();
   using (var memoryStream = new MemoryStream())
   { 
      request.Body.CopyTo(memoryStream);
      request.Body.Position = 0; //add to telemetry properties
   }
}

最佳答案

我也在 Github 上回复了你的帖子。以下是使用 Http Post/Put 请求正文中的信息丰富遥测的正确方法。这是一个 Controller Post Action,RequestTelemetry 中包含来自帖子正文的信息。

[HttpPost]
        public IActionResult Create([FromBody] TodoItem item)
        {
            if (item == null)
            {
                return BadRequest();
            }

            RequestTelemetry requestTelemetry = HttpContext.Features.Get<RequestTelemetry>();
            requestTelemetry.Properties.Add("nameFromBody", item.Name);

            _context.TodoItems.Add(item);
            _context.SaveChanges();

            return CreatedAtRoute("GetTodo", new { id = item.Id }, item);
        }

关于c# - 遥测初始化程序从 .net core MVC 应用程序添加请求正文内容以请求遥测属性不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50280933/

相关文章:

asp.net-mvc - ASP.NET Core FromForm 和 FromBody 相同的操作

c# - Razor Pages - 部分 View 和从模型获取数据的问题

azure - 如何从 Analytics Application Insights 获取 Qna Maker "Q"?

azure - 是否可以在单个 Azure 项目中同时使用 New Relic 和 Azure Application Insights?

c# - Entity Framework 延迟加载的集合有时为空

Asp.net vNext Cookie 身份验证

c# - 运行 selenium 单元测试时 Firefox 崩溃

Azure Application Insights 自定义 Cloud_RoleName 初始值设定项声明方法不起作用

c# - 这个复杂的大东西等于这个吗?或这个?或这个?

c# - 循环中委托(delegate)的异步调用