Answer the question
In order to leave comments, you need to log in
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
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;
}
}
...
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new DecimalFormatConverter());
...
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 questionAsk a Question
731 491 924 answers to any question