1
votes

jquery $.ajax() sends dates from browser as json in ISO format: yy-mm-dd (or I can use yyyy-mm-dd if this is better) in POST body.

ASP.NET MVC4 Web API controller contains DateTime property for this.

How to get date value in any server thread culture settings?

I tried

 public class TestController : ApiController {

    public class PlaaniSisend
    {
        public DateTime date { get; set; }
    }


    [HttpPost]
    public HttpResponseMessage Post([FromBody] PlaaniSisend vali)
    {
      Console.Write(vali.date );
    }
  }

If server thread culture date format is different than ISO, vali.date value is wrong. How to fix this so that ISO date format is uset for parse in any server culture settings ?

2

2 Answers

0
votes

This worked for me: I defined globalization settings in web.config:

<globalization enableClientBasedCulture="false" requestEncoding="utf-8" responseEncoding="utf-8" culture="en-GB" uiCulture="en-GB"/>

and then, in Global.asax.cs > Application_Start, i set JsonFormatter to use the current culture:

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.Culture = System.Globalization.CultureInfo.CurrentCulture;
-2
votes

You can accept the data as string, and parse it with a specific format and culture:

public class TestController : ApiController {

  public class PlaaniSisend
  {
    public string date { get; set; }
  }

  [HttpPost]
  public HttpResponseMessage Post([FromBody] PlaaniSisend vali)
  {
    DateTime date = DateTime.ParseExact(vali.date, "yyyy-MM-dd", CultureInfo.InvariantCulture);
    Console.Write(date);
  }

}