Home > Software engineering >  FromBody binds property with BindNever attribute
FromBody binds property with BindNever attribute

Time:07-08

I have created a DTO:

public class MyDto :
{
    [Required]
    public string Name{ get; set; }

    [BindNever]
    public int X { get; set; }
}

When I sent body to the enpoint:

{  "Name": "name", "X": "9,}

the X is 9 instead of 0, I would expect that [FromBody] will not bind this property.

How to prevent X to be initialized when constructed and pased to a controller action?

CodePudding user response:

From the documentation about [Bind], [BindRequired], [BindNever] :

These attributes affect model binding when posted form data is the source of values. They do not affect input formatters, which process posted JSON and XML request bodies.

That's why you need to add a attribute depending the serializer used. By default in ASP.NET Core, the serializer is "System.Text.Json" and the attribute expected is [JsonIgnore] :

public class MyDto :
{
    [Required]
    public string Name{ get; set; }

    [BindNever]
    [JsonIgnore]
    public int X { get; set; }
}
  • Related