Custom MediaTypeFormatter, why IKeyValueModel, and not my model type?

I am trying to execute a custom implementation of MediaTypeFormatter , but the bool CanReadType(Type type) method is always called with type IKeyValueModel , instead my type is MyProduct .

In my API controller, I:

 [HttpPost] public Task Save(MyProduct product) 

I saw several examples ( example 1 , example 2 ), and I also tried the code:

 protected override bool CanReadType(Type type) { if (type == typeof(IKeyValueModel)) return false; return true; } 

But then I get "MissingMethodException: No parameterless constructor defined for this object" because my model type does not have a constructor without parameters. So it looks like this because CanReadType returns false in IKeyValueModel , the environment uses a different format. In fact, the OnReadFromStreamAsync method never hits.

I want to be able to control how my models are deserialized, I want to get the real type, not IKeyValueModel .

This already worked fine in model-bound MVC.

Greetings.

UPDATE 2012/05/29:

If I remove the default json formatter, it works:

  public static void RegisterApis(HttpConfiguration config) { config.Formatters.Clear(); 

But then I would like to save both, how can I indicate which one I want to use?

Sincerely.

+6
source share
1 answer

If you need to control serialization, it is better to use the flexibility of Json.NET (see here , here and here ) to control, and not to write a formatter like a media just for that.

Json.NET is now the default format in ASP.NET Web APIs.


UPDATE

My objects do not have constructors without parameters and read-only properties. I also have objects that inherit from DynamicObject, so let's say that my business objects are not trivial.

I will probably show you how to shoot in the foot. But I would better explain how to avoid these problems, because I believe that you are using them, since you have anti-patterns.

First of all, what you are looking for is not a different media type format. Do you need another serializer or just need to configure your serializer.

But more importantly, serializing your business units directly to the customer is not such a great idea. We need DTOs, which are called view models here. Such classes are only state holders, no logic, no magic. Serializing them should not be a problem.

You can use AutoMapper, etc. to display your entities for viewing models at no additional development cost. It is always recommended that you distract your domain models from the presentation level.

+3
source

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


All Articles