custom modelmetadataprovider for JsonResult

230 views Asked by At

I wrote a custom metadata provider by inheriting it from DataAnnotationsModelMetadataProvider. The custom provider contains override implementations for GetMetadataforProperty and CreateMetadata.

When I return ActionResult from my controller class method, the code for my custom metadata provider is executed. However if I return JsonResult, the custom metadata provider code is not hit.

Am I missing something? Any help would be appreciated.

1

There are 1 answers

0
Benjamin Gale On

This is the correct behaviour of the MVC framework and what you're asking doesn't actually make sense.

When you return JsonResult from your controller you are simply telling MVC to send JSON formatted content directly to the response. Your controllers action method has already done everything it needs to at this point.

However, If you return an ActionResult of type ViewResult there is further processing that needs to take place before anything is written to the response. The information in your metadata provided is needed when rendering views so the framework will call the metadata provider to provide your views with the required information.

So the reason that your metadata provider is not being called when you return JsonResult is because it is not required.

I would suggest looking at this post which provides a link to a diagram of the MVC pipeline which will help you understand what is going on.