URI的Web API模型绑定 [英] Web API ModelBinding From URI

查看:61
本文介绍了URI的Web API模型绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So I have a custom Model Binder implemented for DateTime type and I register it like below:

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

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

and then I have setup 2 sample actions to see if my custom model binding takes place:

    [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参数没有使用自定义绑定程序绑定

When I run and invoke both actions from mentioned URLs, user's JoinDate property successfully gets bound using the custom binder I configured but BindDateTime's datetime parameter does not get bound using the custom binder.

我已经在配置中指定所有DateTime应该使用我的自定义活页夹,那么为什么会无动于衷?建议得到高度赞赏.

I have already specified in config that all DateTime should use my custom binder then why the indifference? Suggestions are highly appreciated.

CurrentCultureDateTimeAPI.cs:

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,那么它会按预期工作,但是又为什么呢?

NOTE: If I use [FromUri(Binder=typeof(CurrentCultureDateTimeAPI))]DateTime datetime then it works as expected but then again why?

推荐答案

也很令人惊讶:)

我最初的疑问是这条线:

My initial doubt was this line:

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

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

但是出于奇怪的原因,这似乎不适用于这种特定情况.

But for weird reasons this does not seem to work with this particular scenario.

所以

只需在静态类WebApiConfig

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

,这样您的WebAPIConfig文件如下所示:

so that your WebAPIConfig file looks like:

 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已注册.

And everything works fine because this method is directly invoked by WebAPI framework so for sure your CurrentCultureDateTimeAPI gets registered.

在您的解决方案中进行了检查,效果很好.

Checked this with your solution and works great.

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

Note: (From the comments) You can still support Attribute Routing and you need not comment out this line config.MapHttpAttributeRoutes().

但是,如果有人能说出为什么GlobalConfiguration无法解决

But still, It would be great if somebody can tell why GlobalConfiguration does not work out

这篇关于URI的Web API模型绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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