2

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.