Web API ModelBinding From URI

后端 未结 2 1571
自闭症患者
自闭症患者 2021-02-20 06:47

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

void Application_Start(object sender, EventArgs e)
{
            


        
相关标签:
2条回答
  • 2021-02-20 07:20

    Pretty surprising too :)

    My initial doubt was this line:

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

    MSDN says 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.

    So,

    Just add this line inside the static class WebApiConfig

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

    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());
            }
    

    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.

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

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

    0 讨论(0)
  • 2021-02-20 07:25

    It looks like you want to post some data to the server. Try to use FromData and post JSON. FromUri is typically used to fetch some data. Use WebAPI's conventions and allow it to work for you.

    0 讨论(0)
提交回复
热议问题