我有一个在ASP.NET Core 1.0 RC2上运行的控制器,我想将原始POST数据转储到遥测中,因为ApplicationInsights不会为您执行此操作.我的代码看起来像这样
[HttpPost] [Produces("application/json")] public IActionResult Post([FromBody] RequestClass RequestData) { var stream = this.HttpContext.Request.Body; stream.Position = 0; using (var reader = new StreamReader(stream)) { string body = reader.ReadToEnd(); Telemetry.TrackTrace(body,Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Information); } return Ok(); }
但字符串“body”总是空着.如果我从函数签名中删除[FromBody]装饰,那么此代码可以工作,但RequestData对象只包含null,这不是我想要的.
我唯一能想到的就是将RequestData转换回Json字符串,但这感觉很笨拙而且很慢.
(编辑:POST数据是Json)
解决方法
您需要启用缓冲请求正文:
services.Configure< FormOptions>(options => options.BufferBody = true);
https://github.com/aspnet/HttpAbstractions/blob/dev/src/Microsoft.AspNetCore.Http/Features/FormOptions.cs#L20
services.Configure< FormOptions>(options => options.BufferBody = true);
https://github.com/aspnet/HttpAbstractions/blob/dev/src/Microsoft.AspNetCore.Http/Features/FormOptions.cs#L20