gpt4 book ai didi

c# - 何时使用 JsonResult 而不是 ActionResult

转载 作者:IT王子 更新时间:2023-10-29 04:30:53 24 4
gpt4 key购买 nike

关于这个问题,我一直找不到具体的答案。我查看了来自 this 的帖子和后续帖子问题和其他地方,但我真正从阅读中得出的是 JsonResult 具有硬编码的内容类型,并且实际上没有任何性能提升。

如果两个结果都可以返回 Json,为什么您需要使用 JsonResult 而不是 ActionResult。

public ActionResult()
{
return Json(foo)
}

public JsonResult()
{
return Json(bar)
}

谁能解释 ActionResult 根本无法完成工作而 JsonResult 必须 的场景。如果不是,为什么首先存在 JsonResult 。

最佳答案

When to use JsonResult over ActionResult

我通常会返回具体的结果(例如 JsonResultViewResult),我的优点是:

有一些链接支持这种方法:

引用自Pro ASP.NET MVC 3 Framework :

Note Notice that that the return type for the action method in the listing is ViewResult. The method would compile and work just as well if we had specified the more general ActionResult type. In fact, some MVC programmers will define the result of every action method as ActionResult, even when they know it will always return a more specific type. We have been particularly diligent in this practice in the examples that follow to make it clear how you can use each result type, but we tend to be more relaxed in real projects.

只有当操作应该返回不同类型的结果时,我才会使用 ActionResult 而不是具体的结果。但这种情况并不常见。

我还想补充一点,ActionResult 是一个抽象类,因此您不能简单地创建此类型的实例并返回它。 JsonResult 是具体的,因此您可以创建它的实例并从操作方法返回。 There are many other types that derived from ActionResult基本上都是used to override ExecuteResult method .

public abstract class ActionResult
{
public abstract void ExecuteResult(ControllerContext context);
}

该方法由ControllerActionInvoker调用,实现向response对象写入数据的逻辑。

ControllerActionInvoker 不知 Prop 体结果,因此它可以处理从 ActionResult 派生的任何结果并实现 ExecuteResult.

在这两种情况下,您在示例中返回 JsonResult 类型的实例,而 Json(model) 它只是一个创建 JsonResult 实例的工厂方法

还有一个SO问题Is it better to have a method's datatype be as specific as possible or more general?其中讨论了方法参数和返回值的最佳实践

总体思路提供抽象类型作为参数,以便您的方法可以处理更广泛的参数; 返回足够具体的类型,这样您的客户就不需要转换或转换它们。

关于c# - 何时使用 JsonResult 而不是 ActionResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26390806/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com