Pau*_*ett 7 asp.net date-format asp.net-web-api
我希望我的用户能够以英国格式发布日期到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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
在我的 Global.asax.cs 文件中,添加以下行来告诉 api 使用此模型绑定器来获取 DateTime 值:
GlobalConfiguration.Configuration.BindParameter(typeof(DateTime), new DateTimeModelBinder());
Run Code Online (Sandbox Code Playgroud)
这是我的 api 控制器中的方法:
public IList<LeadsLeadRowViewModel> Get([ModelBinder]LeadsIndexViewModel inputModel)
Run Code Online (Sandbox Code Playgroud)
我的 LeadsIndexViewModel 类有几个 DateTime 属性,这些属性现在都是有效的英国日期时间。
| 归档时间: |
|
| 查看次数: |
4570 次 |
| 最近记录: |