Retrieving POST data when using [FromBody]

I have a controller that runs on ASP.NET Core 1.0 RC2, and I would like to reset the original POST data to telemetry since ApplicationInsights does not do this for you. My code is as follows:

[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(); } 

But the line "body" always appears empty. If I remove the [FromBody] decor from the function signature, then this code works, but the RequestData object contains only zero, which I don't want.

The only thing I can think of is converting RequestData back to a Json string, but it seems awkward and slow.

(EDIT: POST data - Json)

+6
source share
3 answers

You need to enable buffering of 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

+8
source

The easiest way to solve this problem is to use jObject as a model. And send the request with Content-Type: application / json in the header.

Use something like NewtonSoft json dll:

 [HttpPost] public IActionResult Post([FromBody] jObject RequestData) { string str = RequestData["key"]; return Ok(); } 

It worked for me

+3
source

The request stream has already been read, so here you can do EnableRewind in the request

See the solution here for reading json from the body . The same goes for your problem.

-one
source

All Articles