Scenario: implementing a standard REST API / GET method on a .net core controller.
The documentation states that OkObjectResult is an ObjectResult with status 200. This is available through the Ok(myResult)
method inherited from ControllerBase. I assume this is a convenience method.
However, the tutorial is not using this approach - it instead returns new ObjectResult(myResult)
which will default to status 200.
Is there any difference between these two approaches?
I can only see the difference in relying on some default value somewhere and providing this value explicitly - the latter is usually better and your intention is much more clear with
OkObjectResult
(or settingStatusCode
explicitly), which is important enough.ObjectResult
does not have defaultStatusCode
of 200 - it actually have this value null by default. However,HttpResponse
has default status code 200, so it works the same anyway.Technically there is no difference between the two approaches.
If you want to look at the code of
OkObjectResult
then you will see that theOkObjectResult
is anObjectResult
that sets the 200 status code, which is the default ofObjectResult
already.The only difference for me is readability in code and your own or your team preferences. It is all about naming and what intention you want to stress.
Update: Both approaches in the original question + the third approach in the accepted answer has now been superseded by simply returning the object directly:
Relevant example and explanation from the current tutorial page: