来自URI的Web API ModelBinding

所以我有一个为DateTime类型实现的自定义Model Binder,我将其注册如下:

 void Application_Start(object sender, EventArgs e) { // Code that runs on application startup GlobalConfiguration.Configuration.BindParameter(typeof(DateTime), new CurrentCultureDateTimeAPI()); } 

然后我设置了2个示例操作以查看我的自定义模型绑定是否发生:

  [HttpGet] public void BindDateTime([FromUri]DateTime datetime) { //http://localhost:26171/web/api/BindDateTime?datetime=09/12/2014 } [HttpGet] public void BindModel([FromUri]User user) { //http://localhost:26171/web/api/BindModel?Name=ibrahim&JoinDate=09/12/2014 } 

当我运行并调用上述URL中的两个操作时, userJoinDate属性使用我配置的自定义绑定器成功绑定,但BindDateTimedatetime参数不会使用自定义绑定器绑定。

我已经在config中指定所有DateTime应该使用我的自定义绑定器然后为什么冷漠? 建议非常感谢。

CurrentCultureDateTimeAPI.cs:

 public class CurrentCultureDateTimeAPI: IModelBinder { public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) { var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); var date = value.ConvertTo(typeof(DateTime), CultureInfo.CurrentCulture); bindingContext.Model = date; return true; } } 

注意:如果我使用[FromUri(Binder=typeof(CurrentCultureDateTimeAPI))]DateTime datetime然后它按预期工作,但又为什么?

非常令人惊讶:)

我最初的疑问是这一行:

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

MSDNGlobalConfiguration => GlobalConfiguration provides a global System.Web.HTTP.HttpConfiguration for ASP.NET application

但由于奇怪的原因,这似乎不适用于这种特殊情况。

所以,

只需在静态类WebApiConfig添加此行

  config.BindParameter(typeof(DateTime), new CurrentCultureDateTimeAPI()); 

以便您的WebAPIConfig文件如下所示:

  public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "web/{controller}/{action}/{datetime}", defaults: new { controller = "API", datetime = RouteParameter.Optional } ); config.BindParameter(typeof(DateTime), new CurrentCultureDateTimeAPI()); } 

一切正常,因为这个方法是由WebAPI framework直接调用的,所以确保你的CurrentCultureDateTimeAPI被注册。

用您的解决方案检查这一点,效果很好。

注意:( 来自注释)您仍然可以支持Attribute Routing ,您无需注释掉此行config.MapHttpAttributeRoutes()

但是,如果有人能说出为什么GlobalConfiguration不能解决问题,那将会很棒

看起来您想要将一些数据发布到服务器。 尝试使用FromData并发布JSON。 FromUri通常用于获取一些数据。 使用WebAPI的约定并允许它为您工作。