I am trying to deserialize an object in a web api controller. It consists of DateTime. Date format. The Time property is dd-MM-YYYY. I set the json serialzer dd-MM-YYYY format in the global.asax file. However, it gives me the error "failed to convert string to date and time."
Attaching both files as an image



------------------ Code in plain text -------------------
The function to run the application file Global.asax
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
AuthConfig.RegisterAuth();
GlobalConfiguration.Configuration.MessageHandlers.Add(new ApiAuthenticationHandler());
JobScheduler.Start();
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
DateFormatString = "dd-MM-yyyy hh:mm tt",
};
var dateTimeConverter = new IsoDateTimeConverter
{
DateTimeFormat = "dd-MM-yyyy hh:mm tt"
};
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings
.Converters.Add(dateTimeConverter);
}
API request
{
"CustomerViewModel": {
"DOB": "18-12-2018",
}
}
API controller
public Guid CustomerSignup(JObject parametrs)
{
dynamic jsonParameters = parametrs;
CustomerViewModel customer = jsonParameters.CustomerViewModel.ToObject<CustomerViewModel>();
if (ModelState.IsValid)
{
try
{
Guid CurrentApplicationId = new Guid(ConfigurationManager.AppSettings["ApplicationId"].ToString());
Logic logic = new Logic(CurrentApplicationId);
Guid result = logic.AddCustomers(customer, false);
if (result != new Guid())
{
logic.SendVerifcationEmail(result, customer.UserName, customer.UserAddress.Email, Request.RequestUri.GetLeftPart(UriPartial.Authority));
return result;
}
else
{
return result;
}
}
catch (Exception ex)
{
if (ex.GetType().Name == "FaultException")
{
throw new FaultException(ex.Message);
}
else
{
throw new FaultException("Fields are not valid.");
}
}
}
else
{
throw new FaultException("Fields are not valid.");
}
}
source
share