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

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

问题描述

作为新的ASP.NET MVC,我一直想知道的控制器方法的签名。在我见过的所有例子,他们似乎总是返回的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.

下面是一个常见的​​例子:

Here's a commonly seen example:

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

在这种情况下,是不是更有意义申报方法公开的ViewResult指数(),并获得更强的类型支持?

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.

我也知道可能存在的多态性的应用场合(例如,如果你只想在某些情况下重定向,但表现在其他情况下的视图),但如果该方法的总是的回报视图,我会找一个的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显然提供了更强大的签名,但如果一个人控制整个code基,它总是可以将方法的签名更改为更普遍的返回类型是否应该成为必要未来。

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 类是当操作方法不同的路径返回不同的亚型。

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.

史蒂芬·桑德森还建议在他的书中临ASP.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,即使他们肯定知道,它总是会返回一个特定的子类。但是,它在面向对象编程一套行之有效的原则方法应返回的最具体类型他们可以(以及接受他们可以最一般的参数类型)。根据这一原则,最大限度地为code调用你的方法,比如单元测试的方便和灵活性。

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

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