Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

FromBody binds property with BindNever attribute

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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; }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading