Must ASP.NET MVC Controller Methods Return ActionResult?

前端 未结 6 753
情书的邮戳
情书的邮戳 2020-12-02 14:24

Being new to ASP.NET MVC, I\'ve been wondering about the signature of Controller methods. In all the examples I\'ve seen, they always seem to return ActionResult, even if th

6条回答
  •  一个人的身影
    2020-12-02 14:50

    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 Pro ASP.NET MVC Framework. 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.

提交回复
热议问题