1

I'm working ASP.NET core C# web api where I need to find and prevent the over posting properties in request body.

For example:

Class:

public class MyClass 
{
 public string Name { get; set; }
 public string Department { get; set; }
}

My controller:

[HttpPost()]
public async Task<IActionResult> Post([FromBody]MyClass myClass )
{
...
return something..
}

My request body:

{
"Name" : "Mage",
"Department" : "IT"
"TotalMarks": "445"
}

here I am passing "TotalMarks" property which is not in the model "MyClass". In this case, the JSON formatter simply ignores this value. (The XML formatter does the same.)

Ref: https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api#data-annotations

But I want to stop and return model validation error, when some properties passed in the API request but those are not the actual model. So is there any common solution for this to support all models.

Magendran V
  • 1,411
  • 3
  • 19
  • 33
  • [This](https://stackoverflow.com/questions/21030712/detect-if-deserialized-object-is-missing-a-field-with-the-jsonconvert-class-in-j) Q&A state that you can set the `MissingMemberHandling` of the Json.net serializer. However im not sure which Json deserializer ASP.NET uses and also not sure how (or if you can) set it – MindSwipe Oct 03 '19 at 12:22

1 Answers1

0

I think in order to achieve what you're asking, you need to implement your own bindingmodel which can be tricky and error prone. There should be no real problem if users send properties not mapped to your model. It will just get discarded by the json serializer.

Instead you should create a Dto model which hides any properties to your domain model you don't want exposed. See this MS article on preventing overposting here: https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-5.0&tabs=visual-studio#prevent-over-posting

M Raymaker
  • 1,231
  • 5
  • 14
  • 31