D
D
dmitrytut2014-03-12 23:57:02
ASP.NET
dmitrytut, 2014-03-12 23:57:02

How to pass Decimal type with different delimiters ('.'\',') in ASP.NET Web Api?

Good afternoon!
The situation is this.
Decimal comes from client, delimiter can be dot or comma (ex. 3.14, 6.62). Due to the Culture settings on the server, the dot option is accepted, but in the case of a comma, this comma is simply removed. It was: 6.62, it came to the controller: 662.
How can I make sure that all decimal types have a comma replaced with a dot when they arrive at the server, or tell me, please, the most correct course of action in my case?
PS
You can write a JSON.Net custom converter, but, as I understand it, you will have to manually apply it to the parameters I need, but I would like it to be applied to all parameters of the decimal type.
Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
dmitrytut, 2014-03-13
@dmitrytut

In general, for those who are interested, I ended up writing a JSON.Net converter that replaces a comma with a dot and registered it globally (it turns out that this is possible) so that all decimals are processed.
Converter:

public class DecimalFormatConverter: JsonConverter
  {
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(decimal) || objectType == typeof(decimal?));
    }

    public override void WriteJson(
      JsonWriter writer, 
      object value, 
      JsonSerializer serializer)
    {
        writer.WriteValue(value);
    }

    public override object ReadJson(
      JsonReader reader, 
      Type objectType, 
      object existingValue, 
      JsonSerializer serializer)
    {
      if (reader.Value != null)
      {
        try
        {
          string replacedValue = reader.Value.ToString().Replace(',', '.');

          return decimal.Parse(replacedValue, CultureInfo.InvariantCulture);
        }
        catch (Exception ex)
        { 
          throw new Exception(
            String.Format("Decimal coverting error. Message: {0}.", ex.Message));
        }
      }
      return null;
    }
  }

And its global registration in the Global.asax.cs file in the Application_Start() method :
...
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new DecimalFormatConverter());
...

But still, it is interesting to listen to the criticism of this approach and the ways to solve it from the category of Best Practices, have you probably come across?

N
Nikolai Turnaviotov, 2014-03-18
@foxmuldercp

Isn't it easier to work with the client's locale and convert it to the desired format?
I will now deal with a similar problem, but I have mvc without json

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question