Ok()方法new ObjectResult()之间有什么区别吗? [英] Is there any difference between the Ok() method new ObjectResult()?

查看:817
本文介绍了Ok()方法new ObjectResult()之间有什么区别吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

方案:在.net核心控制器上实现标准的REST API/GET方法.

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

文档状态OkObjectResult是状态为200的ObjectResult.可通过从ControllerBase继承的Ok(myResult)方法获得.我认为这是一种方便的方法.

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.

但是,教程没有使用此方法-相反,它返回new ObjectResult(myResult),其默认状态为200.

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?

推荐答案

技术上,这两种方法之间没有区别.

Technically there is no difference between the two approaches.

如果您想查看 OkObjectResult ,那么您会看到OkObjectResult是设置了200状态代码的ObjectResult,这是默认的ObjectResult.

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

这篇关于Ok()方法new ObjectResult()之间有什么区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆