Enrico
Enrico

Reputation: 6276

WebApi with .NET core and json validation

I'm creating some webapis with .NET core 2.0. I have a problem with the validation.

[HttpPost]
public async Task<IActionResult> RegisterUser([FromBody] RegistrationModel model) {
    if (model != null && ModelState.IsValid)
    {
        // model is valid
    }
}

The definition of RegistrationModel is for example

public class RegistrationModel
{
    [JsonRequired]
    [JsonProperty("emailAddress")]
    public string EmailAddress { get; set; }

    [JsonRequired]
    [JsonProperty("userCustomerId")]
    public string UserCustomerId { get; set; }
}

If I pass this json, there is a perfect match

{
    "emailAddress" : "[email protected]",
    "userCustomerId" : "b1cb8805-2a59-428e-9c2a-ec663093f84f"
}

My problem is if I pass a json with an extra field, the model still valid.

{
    "emailAddress" : "[email protected]",
    "userCustomerId" : "b1cb8805-2a59-428e-9c2a-ec663093f84f",
    "extraField": "Hello!"
}

Basically, the webapi ignores the extra field but I want to send back and error, something like Model is not valid.

How can I implement that?

Upvotes: 2

Views: 3961

Answers (1)

Christian Sauer
Christian Sauer

Reputation: 10939

This is called overposting, a few mitigation strategies can be found here: https://andrewlock.net/preventing-mass-assignment-or-over-posting-in-asp-net-core/

You can add custom model binders or customized Json deserialization to prevent overposting, but imo it's not worth it - make sure that your models are not vulnerable and move on.

Why?

  1. Be liberal in what you accept.

  2. Sometimes clients send something extra (e.g. an $id property like NewtonSoft.Json sometimes does) and it can be extremely annoying to deactivate that behaviour.

Upvotes: 2

Related Questions