简体   繁体   English

WebApi与.NET核心和json验证

[英]WebApi with .NET core and json validation

I'm creating some webapis with .NET core 2.0. 我正在使用.NET core 2.0创建一些webapis。 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 例如,RegistrationModel的定义

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 如果我通过这个json,那就是完美的匹配

{
    "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. 我的问题是如果我传递带有额外字段的json,模型仍然有效。

{
    "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 . 基本上,webapi忽略了额外的字段,但我想发回和错误,像Model这样的东西是无效的

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/ 这称为叠加,可在此处找到一些缓解策略: 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. 您可以添加自定义模型绑定器或自定义Json反序列化以防止叠加,但是它不值得 - 确保您的模型不易受攻击并继续前进。

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. 有时候客户会发送一些额外的东西(比如像NewtonSoft.Json这样的$ id属性),并且停用这种行为会非常烦人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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