I want to be able to read a request body in an action while still also using default MVC behavior, which involves posting with a [FromBody] parameter. As far as I know I need middleware to accomplish this. My action is:
[HttpPost]
public async Task<JsonResult> ValidateTestFormAsync([FromBody] ValidationRequest<PersonModel> personValidationRequest)
{
Request.EnableBuffering();
Request.Body.Seek(0, SeekOrigin.Begin);
string requestContent;
using (var reader = new StreamReader(Request.Body, Encoding.UTF8, true, 1024, true))
{
requestContent = await reader.ReadToEndAsync();
}
return Json(requestContent);
}
This does not work and requestContent is always null, because once the request is already inside the action, the request body stream has been read and can’t be read again. If I remove [FromBody], it works. I am aware I can write a middleware in the program.cs like so:
app.Use((context, next) =>
{
context.Request.EnableBuffering();
return next();
});
But what are the considerations for that? I don’t want to every request to be bufferable and I still want to pass in the model via [FromBody] to stick with the MVC standard.
I’m basically just trying to run a custom validation where I remove any error messages for fields/properties that were not sent in the post, since MVC always validates the full model and I’m trying to POST field by field. I thought I could compare the ModelState
errors with the posted value keys via the request body, but it seems not possible with my requirements.