Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference between the Ok() method new ObjectResult()?

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?

like image 792
PMBjornerud Avatar asked Sep 15 '16 13:09

PMBjornerud


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 CreatedAtAction?

CreatedAtAction(String, Object, Object) Creates a CreatedAtActionResult object that produces a Status201Created response. CreatedAtAction(String, Object) Creates a CreatedAtActionResult object that produces a Status201Created response.

What is ActionResult in asp net core?

ASP.NET Core includes the ActionResult<T> return type for web API controller actions. It enables you to return a type deriving from ActionResult or return a specific type. ActionResult<T> offers the following benefits over the IActionResult type: The [ProducesResponseType] attribute's Type property can be excluded.


1 Answers

Technically there is no difference between the two approaches.

If you want to look at the code of OkObjectResult then you will see that the OkObjectResult is an ObjectResult that sets the 200 status code, which is the default of ObjectResult 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.

 return Ok(myResult);                  // gives emphasis on status, my personal favorite   return new OkObjectResult(myResult);  // for me a little bit verbose and the same                                        // effect as Ok; but states we return an Object   return new ObjectResult(myResult);    // gives emphasis of the content that is returned 
like image 54
Ralf Bönning Avatar answered Oct 13 '22 21:10

Ralf Bönning