0

I'm trying to disabled default? feature of web api. Currently I have post method in api controller with class as input:

[HttpPost]
public IActionResult MyMethod(MyClass class)

public class MyClass
{
   public bool FirstProp {get;set;}
   public decimal SecondProp {get;set;}
}

that contains bool and decimal required values. When I send json with this values as null, my api behaves ok, it throws exception that value is invalid for specified column.

The problem is when I don't send this column (example json: { }) and I get in controller method class with default values (in my case false for FirstProp type and 0 for SecondProp type). What is the best way to block this kind of serialization/mapping for my post method controller ?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
dawid
  • 11
  • 2

1 Answers1

0

The problem is when I don't send this column (example json: { })

For you do not pass any property,an easier way is to make field required:

public class MyClass
{
    [JsonProperty(Required = Required.Always)]
    public bool FirstProp { get; set; }
    [JsonProperty(Required = Required.Always)]
    public decimal SecondProp { get; set; }
}

For asp.net core 3.x,you need to install Microsoft.AspNetCore.Mvc.NewtonsoftJson and add NewtonsoftJson support like below:

services.AddControllers().AddNewtonsoftJson();

Reference:

https://stackoverflow.com/a/58443810/11398810

Rena
  • 30,832
  • 6
  • 37
  • 72