Search code examples
c#asp.net-coreasp.net-core-mvcasp.net-core-2.1

Using [FromBody] and able to handle an invalid input


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.

  1. How can I achieve that my controller method is being called even with invalid input so I can handle error cases by myself?
  2. Is there a way to write my own middleware for it to log invalid inputs in the way my system needs it or is there even a default one which I could use?

Solution

  • 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?