【发布时间】:2014-09-10 18:17:21
【问题描述】:
所以我有一个为DateTime 类型实现的自定义模型绑定器,我像下面这样注册它:
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 参数没有使用自定义绑定器绑定.
我已经在配置中指定所有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,那么它会按预期工作,但又是为什么?
【问题讨论】:
-
这可能是因为您设置了 [FromUri] 属性 - Web API 使用格式化程序而不是模型绑定,因此不使用您的自定义模型绑定器。尝试删除 BindDateTime 方法中的 [FromUri] 属性。
-
@IlyaLuzyanin 不行。它不起作用。
-
你说得对,[FromUri] 与此无关。我试图重现您的场景 - 一切正常,我的自定义模型绑定器在两种方法中都被调用。能否提供 CurrentCultureDateTimeAPI 代码?
-
@IlyaLuzyanin 当然。现在在帖子里。如果您能提供我的实现的复制代码以供参考,我将不胜感激。
-
好吧,我也很惊讶,你自己试试吧 :) 我试图在 web api 2 源(github.com/ASP-NET-MVC/aspnetwebstack/blob/master/src/… 和 github.com/ASP-NET-MVC/aspnetwebstack/blob/master/src/…)中找到原因,但没有运气。跨度>
标签: c# asp.net-web-api asp.net-web-api2