How to register a custom module model in MVC4 RC WebApi

I recently upgraded from a beta version of MVC4 to RC and ran into a small problem with the WebApi project. One of the first things I noticed was removing ServiceResolver. Before it was deleted, I used it to register the binding provider for a specific model as follows:

IEnumerable<object> modelBinderProviderServices = GlobalConfiguration.Configuration.ServiceResolver.GetServices(typeof(ModelBinderProvider)); List<Object> services = new List<object>(modelBinderProviderServices) { new CustomDynamicObjectModelBinderProvider() }; GlobalConfiguration.Configuration.ServiceResolver.SetServices(typeof(ModelBinderProvider), services.ToArray()); 

The action that this provider of the binder of this model used has the following signature:

 [HttpPut] public void Put(CustomDynamicObject model) 

I tried replacing the old code with the following, but with no results:

 GlobalConfiguration.Configuration.Services.Add(typeof(ModelBinderProvider), new CustomDynamicObjectModelBinderProvider()); 

When I tried to pass data to this action, the GetBinder method of the model provider is not called, and the model parameter is set to null. I was able to do the action using the required model module using the ModelBinder attribute, changing the signature of the Acion / method to the following

 [HttpPut] public void Put([ModelBinder(typeof(CustomDynamicObjectModelBinderProvider))] CustomDynamicObject model) 

While this works, I really would not want to use this syntax in all my controllers / actions.

I think I should mention that my middleware provider inherits from:

 System.Web.Http.ModelBinding.ModelBinderProvider 

I say this because I saw that there is another ModelBinderProvider class in the following namespace:

 Microsoft.Web.Mvc.ModelBinding 

Reminder: how to register custom binding module in MVC4 RC WebApi?

+2
source share
1 answer

Model binding rules in the Web API have changed since the beta. The new rules are described in a post by Mike Stoll . Model binding for complex types now works only if you explicitly add the ModelBinder attribute to the parameter.

The parameter binding mechanism has changed again since the release, so you probably want to wait for RTM before making too many changes. There are several other options in the RC version - depending on the data source that you are trying to link (query string or request body).

  • If the source of your data is the request body, you can create your own MediaTypeFormatter , rather than a model binding:

  • If your data comes from a request and you want to explicitly not include the [ModelBinder] attribute in your parameters, then you can use a combination of a custom TypeConverter and a custom IValueProvider .

In the RTM version (or in night mode), you can use the custom HttpParameterBinding if other parameters do not work.

+7
source

Source: https://habr.com/ru/post/922436/


All Articles