我希望我的用户能够以英国格式发布日期到asp.net web api控制器,例如2012年12月1日(2012年12月1日).
根据我的默认情况,只接受我们的格式.
我可以在某处更改某些内容,以便英国格式是默认格式吗?我尝试在web.config中更改全球化设置,但这没有任何效果.
保罗
解决方法
使用自定义模型绑定器完成此操作,这与MVC3中的模型绑定器略有不同:
public class DateTimeModelBinder : IModelBinder { public bool BindModel(HttpActionContext actionContext,ModelBindingContext bindingContext) { var date = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue; if (String.IsNullOrEmpty(date)) return false; bindingContext.ModelState.SetModelValue(bindingContext.ModelName,bindingContext.ValueProvider.GetValue(bindingContext.ModelName)); try { bindingContext.Model = DateTime.Parse(date); return true; } catch (Exception) { bindingContext.ModelState.AddModelError(bindingContext.ModelName,String.Format("\"{0}\" is invalid.",bindingContext.ModelName)); return false; } } }
在我的Global.asax.cs文件中,添加此行以告诉api将此模型绑定器用于DateTime值:
GlobalConfiguration.Configuration.BindParameter(typeof(DateTime),new DateTimeModelBinder());
这是我的api控制器中的方法:
public IList<LeadsLeadRowViewModel> Get([ModelBinder]LeadsIndexViewModel inputModel)
我的LeadsIndexViewModel类有几个DateTime属性,现在都是有效的UK日期时间.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。