Asp.Net的Web API - 英国公布日期格式 [英] Asp.Net Web Api - posting UK date formats

查看:127
本文介绍了Asp.Net的Web API - 英国公布日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的用户能够发布日期英国格式的asp.net的web API控制器,​​如2012年1月12日(2012年12月1日)。

I want my users to be able to post dates to an asp.net web api controller in uk format, such as 01/12/2012 (1st Dec 2012).

从我可以在默认情况下出来,只有我们格式接受。

From what i can tell by default, only us format is accepted.

我可以改变的地方的东西,使英国的格式是默认?我试图改变全球化在web.config设置,但这没有影响。

Can i change something somewhere so that UK format is the default? I tried changing the globalization setting in the web.config but this had no effect.

推荐答案

完成这个使用自定义的模型绑定,这是在MVC3模型粘合剂稍有不同:

Done this using a custom model binder, which is slightly different to the model binders in 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值:

And in my Global.asax.cs file, add this line to tell the api to use this model binder for DateTime values:

GlobalConfiguration.Configuration.BindParameter(typeof(DateTime), new DateTimeModelBinder());

下面是我的API控制器的方法:

Here is the method in my api controller:

public IList<LeadsLeadRowViewModel> Get([ModelBinder]LeadsIndexViewModel inputModel)

我LeadsIndexViewModel类有哪些是现在所有有效日期英国几个时代的DateTime属性。

My LeadsIndexViewModel class had several DateTime properties which were now all valid UK date times.

这篇关于Asp.Net的Web API - 英国公布日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆