DuncanMack
DuncanMack

Reputation: 340

How to return localized content from WebAPI? Strings work but not numbers

Given this ApiController:

public string TestString() {
    return "The value is: " + 1.23;
}

public double TestDouble() {
    return 1.23;
}

With the browser's language set to "fr-FR", the following happens:

/apiController/TestString yields

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">The value is: 1,23</string>

/apiController/TestDouble yields

<double xmlns="http://schemas.microsoft.com/2003/10/Serialization/">1.23</double>

I would expect TestDouble() to yield 1,23 in the XML. Can anyone explain why this isn't the case and, more importantly, how to make it so that it does?

Upvotes: 0

Views: 576

Answers (1)

Thuan
Thuan

Reputation: 1628

It is because the conversion from double to string happens at different stage for each API. For the TestString API, double.ToString() is used to convert the number to a string using CurrentCulture of the current thread and it happens when the TestString method is called. Meanwhile, the double number which is returned by TestDouble is serialized to string during the serialization step which uses GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Culture. In my opinion, both should use InvariantCulture. On the consumer side, the values will be parsed and be formatted with the correct culture.

Update: this is only used for JsonFormatter. XmlFormatter doesn't have such a setting.

Update 2: It seems (decimal) numbers need special converter to make it culture-aware: Handling decimal values in Newtonsoft.Json

Btw, if you want o change data format per action/request, you can try the last piece of code of the following link: http://tostring.it/2012/07/18/customize-json-result-in-web-api/

Upvotes: 1

Related Questions