使用[FromBody]时获取原始POST数据 [英] Getting hold of raw POST data when using [FromBody]

查看:467
本文介绍了使用[FromBody]时获取原始POST数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在ASP.NET Core 1.0 RC2上运行的控制器,我想将原始POST数据转储到遥测中,因为ApplicationInsights不会为您执行此操作.我的代码看起来像这样

I have a controller running on ASP.NET Core 1.0 RC2 and I'd like to dump the raw POST data out to telemetry as ApplicationInsights doesn't do this for you. My code looks like this

[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,这不是我想要的.

But the string "body" always comes up empty. If I remove the [FromBody] decoration from the function signature, then this code works, but the RequestData object only contains null, which isn't what I want.

我唯一能想到的就是将RequestData转换回Json字符串,但这感觉很笨拙而且很慢.

The only thing I can think of is converting RequestData back to a Json string, but this feels clunky and slow.

(POST数据为Json)

( The POST data is Json)

推荐答案

您需要启用对请求正文的缓冲: services.Configure<FormOptions>(options => options.BufferBody = true); https://github.com/aspnet/HttpAbstractions/blob/dev/src/Microsoft.AspNetCore.Http/Features/FormOptions.cs#L20

You need to enable buffering the request body: services.Configure<FormOptions>(options => options.BufferBody = true); https://github.com/aspnet/HttpAbstractions/blob/dev/src/Microsoft.AspNetCore.Http/Features/FormOptions.cs#L20

这篇关于使用[FromBody]时获取原始POST数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆