asp.net-coremodel-view-controllerjsonresult

Controller and JsonResult asp.net core


Why do i need to inherit from Controller to return JsonResult?

What is the mechanism that makes the JsonResult type available?

I've tried thinking on it and I figure maybe Controller declares it as a type, but I don't know.


Solution

  • You will need to inherit from Controller in order to use the Controller.Json utility method. You will however not need to inherit from Controller just to create a JsonResult. You can always just new-up one. As long as you are within a controller (not necessarily one that inherits Controller), this will still work:

    return new JsonResult(object);
    

    As for why you will need to inherit from Controller and not just ControllerBase; many of the result utility methods actually live in Controller. The reason for this is that those are targeted to view-centric controllers while ControllerBase is typically used for API controllers.

    Now one would think that returning JSON results would be especially useful for API controllers but that is actually not the case: For API controllers, you should rather return an ObjectResult and have the conventions take care of serializing that into the format that was requested by the client. That way, an API controller can easily support formats like JSON and XML at the same time.