Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between ObjectResult and JsonResult

There are two classes in Microsoft.AspNetCore.Mvc namespace:

ObjectResult and JsonResult.

Both convert the returned object in the JSON format.

What is difference between them and what is the purpose to use them?

like image 469
hcp Avatar asked Aug 05 '16 11:08

hcp


People also ask

What is ObjectResult?

ObjectResult is an IActionResult that has content negotiation built in. Inside its ExecuteResultAsync , responsible for writing to the response stream, the framework will walk through the available formatters and select a relevant one.

What is the difference between JsonResult and ActionResult?

Use JsonResult when you want to return raw JSON data to be consumed by a client (javascript on a web page or a mobile client). Use ActionResult if you want to return a view, redirect etc to be handled by a browser.


1 Answers

JsonResult is an IActionResult which formats the given object as JSON

ObjectResult is an IActionResult that has content negotiation built in.

Inside its ExecuteResultAsync, responsible for writing to the response stream, the framework will walk through the available formatters and select a relevant one.

The logic for choosing a formatter is similar to that in ASP.NET Web API, and based on the following order of precedence:

  • Accept header
  • Content-Type header
  • selection based on type match

OkObjectResult Class

An Microsoft.AspNetCore.Mvc.ObjectResult that when executed performs content negotiation, formats the entity body, and will produce a Microsoft.AspNetCore.Http.StatusCodes.Status200OK response if negotiation and formatting succeed.

References:

  • Migrate from ASP.NET MVC to ASP.NET Core MVC
  • Asp.Net Documentation: JsonResult Class
  • Asp.Net Documentation: ObjectResult Class
  • Asp.Net Documentation: OkObjectResult Class
like image 77
Nkosi Avatar answered Oct 06 '22 16:10

Nkosi