简体   繁体   中英

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" : "test.email@gmail.com",
    "userCustomerId" : "b1cb8805-2a59-428e-9c2a-ec663093f84f"
}

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

{
    "emailAddress" : "test.email@gmail.com",
    "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?

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 (eg an $id property like NewtonSoft.Json sometimes does) and it can be extremely annoying to deactivate that behaviour.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM