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

后端 未结 3 581
悲&欢浪女
悲&欢浪女 2021-01-01 09:21

Scenario: implementing a standard REST API / GET method on a .net core controller.

The documentation states that OkObjectResult is an ObjectResult with status 200. T

3条回答
  •  一个人的身影
    2021-01-01 09:44

    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
    

提交回复
热议问题