Problem when converting text to decimal in ASP.NET Core deserialization

Asked

Viewed 94 times

0

Hello,

I have an ASP.NET Core Api that takes as parameter a raw body object from the request.

[HttpPost]

public HttpResponseMessage DoIt([FromBody]DoItDto dto)

My Doitdto class has a decimal property:

public decimal Valor { get; set; }

When I call my api passing as parameter the value without the quotes and with a zero left my Modelstate is invalid and with the following message:

Input string '0208' is not a Valid decimal. Path 'value', line 4, position 15.

{
  "valor": 0208
}

But when I call with the value field filled with quotes, or without the left zero the API works normally and the Modelstate becomes valid:

{
  "valor": 208
}

Or

{
  "valor": "0208"
}

Can anyone explain to me why this happens and how I could call the API by passing the value without quotation marks and with zero left without causing a problem in converting to decimal?

  • if the field is numeric (decimal), pq should it have a left zero? numeric attributes do not have that, only strings. If you pass with quotation marks, you end up being converted, so you accept to arrive with zero left, but if the attributes are numerical, it should be passed without quotation marks and without zero left, after all it is a number

  • Hello @Ricardopunctual. As is a public api that will be called by hundreds of external customers I can’t control how customers will call. To make an api as resilient as possible we need to cover all possible scenarios and one of the clients called the api of this using the value 0208, I could not find a documentation that explains why the "0208" with quotation marks is accepted and not the 0208 without quotation marks. So we’re trying to fulfill the customer’s request.

  • 1

    Hello @Thiago Jordan, good evening, I researched this topic and found this topic and found interesting, maybe answer your question: https://stackoverflow.com/questions/46345894/numbers-cannot-begin-with-a-zero-in-json I hope it helps.

  • Hi @Jeansena, thank you so much for the research. This was the basis I needed to justify not allowing the value to have a zero left in json.

1 answer

0

In fact, you don’t pass a zero on a numerical type. If this check is so important to you, I suggest you turn your DTO.Value into string, and do the numerical processing after the request reaches the controller.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.