来自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中的两个操作时, user
的JoinDate
属性使用我配置的自定义绑定器成功绑定,但BindDateTime
的datetime
参数不会使用自定义绑定器绑定。
我已经在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());
MSDN称GlobalConfiguration
=> 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的约定并允许它为您工作。
- 名为“DefaultApi”的路径已在路径集合中
- 在Asp.Net MVC Web Api中测试Controller时,ModelState.IsValid始终为true
- 要调用此方法,“Membership.Provider”属性必须是“ExtendedMembershipProvider”的实例
- Autofac – 无法创建请求生命周期范围,因为HttpContext不可用 – 由于异步代码?
- 在文档中对API方法进行分组 – 是否存在一些自定义属性
- 具有路由属性的不明确控制器名称:具有相同名称和不同命名空间的控制器,用于版本控制
- 如何阻止HttpClient.GetAsync(uri)挂起?
- 如何在Azure上的Application Insights中将exception链接到请求?
- 安装CORS后无法加载文件