I try to apply back end validation whenever empty or invalid values are send to ASP.NET Core Web API endpoint, but I can't figure out how to handle model binding failure errors.
Getting this error probably from ModelState
when submitting invalid values: totalPrice: ["Could not convert string to decimal: . Path 'totalPrice', line 1, position 71."]
0: "Could not convert string to decimal: . Path 'totalPrice', line 1, position 71."
It looks like model binding is failing and error is displayed directly to the client.
I have pretty simple controller decorated with ApiController
attribute.
[ApiController]
public class ProductsController
{
[HttpPost]
public IActionResult Post([FromBody]CreateProductDto model)
{
model.Id = await service.CreateProduct(model);
return CreatedAtRoute(
routeName: "GetProduct",
routeValues: new { id = model.Id },
value: model
);
}
}
and my DTO model
public class CreateProductDto
{
[Required(ErrorMessage = "Invalid value")]
public decimal totalPrice { get; set;}
public int count { get; set; }
}
Is there a way to customize the text from model binding errors? I would like to prevent sensitive info to be send and provide friendly feedback to the client?