将日期参数传递给对MVC操作的ajax调用的安全方法

我有一个MVC操作,它的一个参数是一个DateTime ,如果我传递“17/07/2012”,它会抛出一个exception,说param为null但不能01/07/2012值,但如果我通过01/07/2012它被解析为Jan 07 2012

我将日期传递给DD/MM/YYYY格式的ajax调用,我应该依赖MM/DD/YYYY格式,尽管在web.config配置了文化?

这是一个简单的方法,只有一个日期参数。

在Asp.NET-MVC中有三个安全选项来发送日期参数:

  • YYYY/MM/DD发送它是国际日期的ISO标准。
  • 使用POST请求而不是GET请求。

  • 如果要更改默认Model Binder绑定器绑定日期的方式:

您可以使用IModelBinder更改默认模型绑定器以使用用户区域性

 public class DateTimeBinder : IModelBinder { public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); var date = value.ConvertTo(typeof(DateTime), CultureInfo.CurrentCulture); return date; } } 

并在Global.Asax写道:

 ModelBinders.Binders.Add(typeof(DateTime), new DateTimeBinder()); ModelBinders.Binders.Add(typeof(DateTime?), new DateTimeBinder()); 

阅读这篇优秀的博客 ,了解Mvc框架团队为所有用户实施默认文化的原因。

gdoron的答案对于将日期作为查询字符串传递是正确的。 但是,如果它们作为表单值传递(post值),则应使用正确的文化(假设文化已配置属性)。