ASP.NET MVC 控制器方法必须返回 ActionResult 吗? [英] Must ASP.NET MVC Controller Methods Return ActionResult?

查看:22
本文介绍了ASP.NET MVC 控制器方法必须返回 ActionResult 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为 ASP.NET MVC 的新手,我一直想知道 Controller 方法的签名.在我见过的所有示例中,它们似乎总是返回 ActionResult,即使它们实际上返回 ViewResult 实例或类似实例.

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 they actually return a ViewResult instance or similar.

这是一个常见的例子:

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

在这种情况下,将方法声明为public ViewResult Index(),并获得更强的类型支持不是更有意义吗?

In such a case, wouldn't it make more sense to declare the method as public ViewResult Index(), and get stronger type support?

实验表明这是可行的,所以它似乎是可能的.

Experimentation indicates that this works, so it seems possible.

我确实意识到可能存在需要多态性的情况(例如,如果您只想在某些情况下重定向,但在其他情况下显示视图),但如果方法 always 返回视图,我会发现 ViewResult 更可取.

I do realize that there may be situations where the polymorphism is desired (e.g. if you want to redirect only in certain situations, but show a view in other situations), but if the method always returns a view, I'd find a ViewResult more desirable.

就未来的兼容性而言,ActionResult 显然提供了更健壮的签名,但如果一个人控制了整个代码库,那么如果将来需要的话,总是可以将方法的签名更改为更通用的返回类型.

In terms of future compatibility, ActionResult obviously provides a more robust signature, but if one controls the entire code base, it's always possible to change a method's signature to a more general return type if that should become necessary in the future.

是否还有其他我不知道的注意事项,或者我应该继续使用特定的返回类型声明我的控制器方法?

Are the any other considerations that I'm not aware of, or should I just go ahead and declare my controller methods with specific return types?

推荐答案

您绝对可以使用特定的返回类型,即使网络上的大多数示例似乎返回 ActionResult.我唯一会返回 ActionResult 类的情况是 action 方法的不同路径返回不同的子类型.

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 还建议在他的书中返回特定类型 ProASP.NET MVC 框架.看看下面的报价:

Steven Sanderson also recommends returning specific types in his book Pro ASP.NET MVC Framework. Take a look at the quote below:

这个动作方法特别声明它返回一个 ViewResult 的实例.如果改为该方法,它的工作原理是一样的返回类型是 ActionResult(所有操作结果的基类).事实上,一些 ASP.NET MVC 程序员声明了他们所有的动作方法作为返回一个非特定的 ActionResult,即使他们肯定知道它将始终返回一个特定的子类.然而,这是一个面向对象编程中公认的原则,即方法应该返回他们可以返回的最具体的类型(以及接受他们可以使用的最通用的参数类型).遵循这个原则最大限度地提高调用您的方法的代码的便利性和灵活性,比如你的单元测试.

这篇关于ASP.NET MVC 控制器方法必须返回 ActionResult 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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