Hi @Newbie Dev ,
Can someone please give me an example of how they are different?
What will be the output of each of them?
If you check the Ok constructor method, you can see that:
When using the Ok
method without parameter, it will return an OkResult
object. If using the Ok
method with the parameter (an object), it will return an OkObjectResult
object.
The difference between OkResult and OkObjectResult as the document and Bruce-SqlWork said, the OkResult will show an empty 200 response, and the OkObjectResult will show the 200 responses with the passed object.
So, the code return Ok();
equals return new OkResult();
, and the code return Ok(object);
equals return new OkObjectResult(object);
. The only difference for me is readability of code and your own or your team preferences.
The result is like this:
using OkObjectResult
or Ok(object)
:
public IActionResult Index2()
{
return new OkObjectResult(new { userid=101, username="Tom"}); // or using return Ok(new { userid=101, username="Tom"});
}
Using OkResult
or Ok()
:
public IActionResult Index2()
{
return new OkResult(); // Or using return Ok();
}
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion