I do not want do bind the Id
property on my CustomerViewModel
so I added a [BindNever]
attribute but it is not working. What could be the solution?
I have the following:
CustomerController.cs
// PUT api/customers/5
[HttpPut("{id}")]
public async Task<IActionResult> Put([FromUri] int id, [FromBody]CustomerViewModel customer)
{
//Implementation
}
CustomerViewModel
public class CustomerViewModel
{
[BindNever]
public int Id { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public string Email { get; set; }
}
If I input the following json . The id
property still gets binded
{
"id": 100,
"lastName": "Bruce",
"firstName": "Wayne",
"email": "[email protected]"
}
For example, “BindNever” attribute is used to tell Model binding, which does not bind any value to this parameter. This attribute tells to the Model binder to not to bind the value with the parameter. This attribute tells the Model binder that binding is required. If binding is not found, this attribute adds the error to the model state.
MVC doesn’t throw any error, when binding fails. There are many attributes contained by MVC, which help us control the behavior of the Model binding. For example, “BindNever” attribute is used to tell Model binding, which does not bind any value to this parameter. This attribute tells to the Model binder to not to bind the value with the parameter.
This attribute tells to the Model binder to not to bind the value with the parameter. This attribute tells the Model binder that binding is required. If binding is not found, this attribute adds the error to the model state.
Asp.Net Core Model Binding has a set of attributes that gives us the ability to control from what source we want to receive the binding data. In this post I’m going to go through these attributes and show how and when you can use them.
I add a note.
Now it's officially explained by Microsoft.
https://docs.microsoft.com/ja-jp/aspnet/core/mvc/models/model-binding?view=aspnetcore-6.0#attributes-for-complex-type-targets
https://docs.microsoft.com/ja-jp/aspnet/core/mvc/models/model-binding?view=aspnetcore-6.0#input-formatters
https://docs.microsoft.com/ja-jp/aspnet/core/mvc/models/model-binding?view=aspnetcore-6.0#frombody-attribute
In summary,
If we use the “FromBody attribute (including defaults such as HttpPost attribute)”, it depends on the input formatter and the BindNever attribute etc. will not work.
Instead, we can do so by specifying the attribute that corresponds to the input formatter. For example, for the default json It can be ignored using "System.Text.Json.Serialization.JsonIgnoreAttribute".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With