C# 自定义日期时间模型绑定器不工作
我正在使用Asp.Net MVC 4,这是我的自定义模型活页夹:C# 自定义日期时间模型绑定器不工作,c#,asp.net,asp.net-mvc,asp.net-mvc-4,datetime,C#,Asp.net,Asp.net Mvc,Asp.net Mvc 4,Datetime,我正在使用Asp.Net MVC 4,这是我的自定义模型活页夹: public class DateTimeModelBinder : DefaultModelBinder { private string _customFormat; public DateTimeModelBinder(string customFormat) { _customFormat = customFormat; }
public class DateTimeModelBinder : DefaultModelBinder
{
private string _customFormat;
public DateTimeModelBinder(string customFormat)
{
_customFormat = customFormat;
}
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if(value != null)
return DateTime.ParseExact(value.AttemptedValue, _customFormat, CultureInfo.InvariantCulture);
return null;
}
}
这是我的Web API方法:
[HttpPost]
public HttpResponseMessage Register(RegistrationUser registrationUser)
{
if (ModelState.IsValid)
{
return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("User is created") };
}
else
{
return new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content =
new ObjectContent<IEnumerable<string>>(ModelState.Values.SelectMany(f => f.Errors.Select(s => s.ErrorMessage)),
new JsonMediaTypeFormatter())
};
}
}
这是我的注册用户POCO:
public class RegistrationUser
{
public int UserID { get; set; }
[Required(ErrorMessage = "Email address is required")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string EmailAddress { get; set; }
[Required(ErrorMessage = "First Name is required")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Last Name is required")]
public string LastName { get; set; }
[Required(ErrorMessage = "Password is required")]
public string Password { get; set; }
[NullableRequired(ErrorMessage = "Gender is required")]
public short? GenderID { get; set; }
[NullableRequired(ErrorMessage = "Birth Date is required")]
public DateTime? BirthDate { get; set; }
[NullableRequired(ErrorMessage = "Profile For is required")]
public short? ProfileForID { get; set; }
}
我错过了什么
PS:如果我添加一个属性
[ModelBinder(typeof(DateTimeModelBinder))]
public class RegistrationUser
它可以很好地工作,但这是乏味和耗时的,而且容易出错。我不想把它添加到每个模型中。我希望DateTimeModelBinder
应始终用于DateTime
和DateTime?
更新:
看起来我需要使用JSON.Net的转换器功能:
public class DateTimeConverter : DateTimeConverterBase
{
private string _dateFormat;
public DateTimeConverter(string dateFormat)
{
_dateFormat = dateFormat;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
try
{
if (reader.Value != null && reader.Value.ToString().Trim() != string.Empty)
return DateTime.ParseExact(reader.Value.ToString(), _dateFormat, CultureInfo.InvariantCulture);
}
catch
{
}
return null;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(((DateTime)value).ToString(_dateFormat));
}
}
然后我不得不在WebApiConfig中添加以下内容:
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(
new DateTimeConverter("dd/mm/yyyy"));
而且它有效 看起来您正在编写MVC模型绑定器,并试图在Web API控制器中使用它。这两个系统相似,但在使用的类型方面不兼容
System.Web.Mvc
命名空间中的类型都是Mvc,而System.Web.Http
命名空间中的类型都是Web API
MVC和WebAPI模型绑定的注册在某些方面也很相似,但在其他方面有所不同。例如,您可以对所讨论的类型使用[ModelBinder(typeof(XyzModelBinder))]
属性在两个系统中声明模型绑定器。但全局模型绑定器的注册是不同的
在MVC中注册全局模型绑定器,如下所示:
ModelBinders.Binders.Add(typeof(Xyz), new XyzModelBinder(...));
在Web API中是这样的:
GlobalConfiguration.Configuration.Services.Add(typeof(ModelBinderProvider), new XyzModelBinderProvider());
关于MVC与Web API,请检查您是否混淆了这些类型-许多类型具有相同或相似的名称,只是它们位于不同的名称空间中。看起来您正在编写MVC模型绑定器,并试图在Web API控制器中使用它。这两个系统相似,但在使用的类型方面不兼容
System.Web.Mvc
命名空间中的类型都是Mvc,而System.Web.Http
命名空间中的类型都是Web API
MVC和WebAPI模型绑定的注册在某些方面也很相似,但在其他方面有所不同。例如,您可以对所讨论的类型使用[ModelBinder(typeof(XyzModelBinder))]
属性在两个系统中声明模型绑定器。但全局模型绑定器的注册是不同的
在MVC中注册全局模型绑定器,如下所示:
ModelBinders.Binders.Add(typeof(Xyz), new XyzModelBinder(...));
在Web API中是这样的:
GlobalConfiguration.Configuration.Services.Add(typeof(ModelBinderProvider), new XyzModelBinderProvider());
关于MVC与Web API,请检查您是否混淆了这些类型-许多类型具有相同或相似的名称,只是它们位于不同的名称空间中。很抱歉,我不明白。你能给我寄一份工作样品吗?模型绑定器如何在web api中工作?System.Web中没有DefaultModelBinder。Http@Jack没有
DefaultModelBinder
,但考虑到您正在实现所有自定义功能,您可以直接实现System.Web.Http.ModelBinding.IModelBinder
接口,因为它的形状基本相同。@Jack我对我的回答做了一些编辑以澄清问题再举一些例子。嗯,看起来我走错方向了。我只想把日期时间转换成特定的格式。我在错误的方向上浪费了很多时间。请在2分钟后检查我的编辑,让我知道你的想法。@Jack啊,如果你只需要决定JSON日期的格式,你的新代码很可能就是你所需要的。对不起,我不明白。你能给我寄一份工作样品吗?模型绑定器如何在web api中工作?System.Web中没有DefaultModelBinder。Http@Jack没有DefaultModelBinder
,但考虑到您正在实现所有自定义功能,您可以直接实现System.Web.Http.ModelBinding.IModelBinder
接口,因为它的形状基本相同。@Jack我对我的回答做了一些编辑以澄清问题再举一些例子。嗯,看起来我走错方向了。我只想把日期时间转换成特定的格式。我在错误的方向上浪费了很多时间。请在2分钟后检查我的编辑,让我知道你的想法。@Jack啊,如果你只需要决定JSON日期的格式,你的新代码很可能就是你所需要的。最好提供你的解决方案作为答案,而不是UPD或其他什么。最好提供你的解决方案作为答案,不像UPD或其他什么