加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

Asp.Net Web Api – 发布英国日期格式

发布时间:2020-12-16 04:09:15 所属栏目:asp.Net 来源:网络整理
导读:我希望我的用户能够以英国格式发布日期到asp.net web api控制器,例如2012年12月1日(2012年12月1日). 根据我的默认情况,只接受我们的格式. 我可以在某处更改某些内容,以便英国格式是默认格式吗?我尝试在web.config中更改全球化设置,但这没有任何效果. 保罗
我希望我的用户能够以英国格式发布日期到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日期时间.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读