When using [FromBody]
in a controller in ASP.NET Core (2.1 in this case), it handles all conversions to the specified model and makes sure the model is valid. This means that the controller method won't even get called if the supplied input is malformed.
In asp.net core 2.1 the ApiController
attribute has been introduced as the way to opt in to Web API-specific conventions and behaviors. Use the CompatibilityVersion.Version_2_1
flag in startup to set the level of compatibility.
The new behaviour is that validation errors will automatically trigger an HTTP 400 response. As described in the documentation, it is quite easy to suppress this behaviour:
services.Configure<ApiBehaviorOptions>(options =>
{
options.SuppressModelStateInvalidFilter = true;
});
In that case you can validate the models as usual:
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
As for your second question, this is too broad:
... to log invalid inputs in the way my system needs it ...
There are filters (like ExceptionFilterAttribute
) that you can use. Perhaps that is what you are looking for?