且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

URI的Web API模型绑定

更新时间:2023-02-15 12:16:26

也很令人惊讶:)

我最初的疑问是这条线:

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