I'm having some problems with Web.API and cultures.
For example (more elaborate example below)
The client sends the number: 500.000
and it gets interpreted as five hunderd
instead of five hunderd thousand
.
I've come across this problem with Windows Forms applications
. There i would just set the culture for the thread
. But using Web.Api (which is totally new to me) i needed to change my tactic
.
My searches have supplied me with several promising solutions but none seem to work sofar.Any got any pointers for me or could point me to the correct solution?
Some examples used:
Solution 1: In the web.config of the webservice: supply the culture under system.web
<system.web>
<globalization enableClientBasedCulture="false" culture="nl-BE" uiCulture="nl-BE"/>
</system.web>
Solution 2: In the construtor of my controller
CultureInfo ci = new CultureInfo("nl-BE");
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
Solution 3: Editing global.asax Used the solution mentionned here but no dice.
or
protected void Application_BeginRequest(object sender, EventArgs e)
{
CultureInfo newCulture = (CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
newCulture.NumberFormat.NumberDecimalSeparator = ",";
newCulture.NumberFormat.NumberGroupSeparator = ".";
Thread.CurrentThread.CurrentCulture = newCulture;
Thread.CurrentThread.CurrentUICulture = newCulture;
}
Some code:
The object:
public class Book
{
public String Author {get; set;}
public String Title {get; set;}
public Double Price {get; set;}
}
The Json sent by the client:
{ "Author": "User09","Title": "User09 The biography", "Price":"50,39" }
=> With the meaning of 50 euros and 39 cents
The function:
[HttpPost]
public String StoreNewObject(Book myBook)
{
// myBook.Price already contains 5039.0 (as in 5039 euros and 0 cents) here before the first line of code is executed.
...
}
My dwindeling patience thanks the.
Note: The application is limited to .Net 4.0
Note 2: Found one working (Ugly Solution) Changed my model as follows:
public class Book
{
public String Author {get; set;}
public String Title {get; set;}
public String Price {
get { return PriceValue.ToString();
set {
CultureInfo ci = new CultureInfo("nl-BE");
PriceValue = Math.Round(Convert.ToDouble(value, ci),2);
}
}
public Double PriceValue {get; set;}
}
In this case PriceValue will contain the correct value.