加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 为什么大多数MVC样本控制器代码都返回ActionResu

发布时间:2020-12-16 07:09:16 所属栏目:asp.Net 来源:网络整理
导读:只是想知道为什么我在示例MVC代码中看到的几乎每个控制器方法都返回ActionResult,即使代码只能返回一种类型的结果.我知道有些情况需要保证,因为你可能会根据逻辑返回RedirectResult或ViewResult,但对于我见过的大多数方法来说情况并非如此. 是不是等于在方法
只是想知道为什么我在示例MVC代码中看到的几乎每个控制器方法都返回ActionResult,即使代码只能返回一种类型的结果.我知道有些情况需要保证,因为你可能会根据逻辑返回RedirectResult或ViewResult,但对于我见过的大多数方法来说情况并非如此.

是不是等于在方法上有一个返回类型的’对象’?为什么不直接指定JsonResult,或FileResult或ViewResult作为返回类型?我没有看到在每个控制器方法上将返回类型设置为ActionResult的好处吗?

经典例子:

public ActionResult Index()
{
    return View();
}

为什么这似乎是常态而不是这个:

public ViewResult Index()
{
    return View();
}

编辑:到目前为止,除了一个以外的所有响应都表明ActionResult更通用.我知道的很多. :)为什么这是在控制器方法上接受的练习,而不是其他地方?您不仅要返回普通方法中可以使用的类型的最高级别基类,而是尝试返回通常可以使用的最具体类型.是什么让控制器方法变得如此不同以至于博主和“示例代码编写者”(是的,我将这个术语提升了)只会诉诸于返回ActionResult?

解决方法

从SO上接受的答案中引用了varbatim.我感觉合理:

Must ASP.NET MVC Controller Methods Return ActionResult?

You can absolutely use specific return
types,even though most examples on
the web seems to return the
ActionResult. The only time I would
return the ActionResult class is when
different paths of the action method
returns different subtypes.

Steven Sanderson also recommends
returning specific types in his book
07001. Take a look
at the quote below:

This action method specifically
declares that it returns an instance
of ViewResult. It would work just the
same if instead the method return type
was ActionResult (the base class for
all action results). In fact,some
ASP.NET MVC programmers declare all
their action methods as returning a
nonspecific ActionResult,even if they
know for sure that it will always
return one particular subclass.
However,it’s a well-established
principle in object-oriented
programming that methods should return
the most specific type they can (as
well as accepting the most general
parameter types they can). Following
this principle maximizes convenience
and flexibility for code that calls
your method,such as your unit tests.

也可以看看:

http://www.bengtbe.com/blog/post/2009/07/01/Use-specific-return-types-in-your-ASPNET-MVC-action-methods.aspx

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读