asp.net-mvc ASP.NET MVC 控制器方法是否必须返回 ActionResult?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1021568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-07 23:39:51  来源:igfitidea点击:

Must ASP.NET MVC Controller Methods Return ActionResult?

asp.net-mvcpolymorphismactionresultviewresult

提问by Mark Seemann

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.

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

Here's a commonly seen example:

这是一个常见的例子:

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

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

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

Experimentation indicates that this works, so it seems possible.

实验表明这是有效的,所以它似乎是可能的。

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 alwaysreturns a view, I'd find a ViewResult more desirable.

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

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.

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

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?

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

回答by BengtBe

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 ActionResultclass is when different paths of the action method returns different subtypes.

您绝对可以使用特定的返回类型,即使网络上的大多数示例似乎都返回ActionResult。我唯一会返回ActionResult类的时候是当动作方法的不同路径返回不同的子类型时。

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

Steven Sanderson 在他的书Pro ASP.NET MVC Framework 中还建议返回特定类型。看看下面的报价:

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.

这个 action 方法专门声明它返回一个 ViewResult 的实例。如果方法返回类型是 ActionResult(所有操作结果的基类),则它的工作原理相同。事实上,一些 ASP.NET MVC 程序员将他们所有的操作方法声明为返回一个非特定的 ActionResult,即使他们确定它总是返回一个特定的子类。然而,在面向对象的编程中,方法应该返回最具体的类型(以及他们可以接受的最通用的参数类型),这是一个既定的原则。遵循此原则可以最大限度地提高调用您的方法的代码的便利性和灵活性,例如您的单元测试。

回答by Paco

Always return the most accurate type you can return. So you should return a ViewResult when the action always shows a view. I would only use ActionResult when you return in ViewResult in some cases (invalid posted data) or a RedirectToRouteResult in other cases.

始终返回您可以返回的最准确的类型。因此,当操作始终显示视图时,您应该返回 ViewResult。当您在某些情况下(无效的发布数据)或 RedirectToRouteResult 在其他情况下返回 ViewResult 时,我只会使用 ActionResult 。

With some advanced actionfilter/executing scenario's, you can even return totally different things that have nothing to do with ActionResult.

使用一些高级的 actionfilter/executing 场景,您甚至可以返回与 ActionResult 无关的完全不同的东西。

回答by Carl

[Partial answer]: You don't always return ActionResult, no. Here's a quick view of some other results you can return: http://msdn.microsoft.com/en-us/library/dd410269%28v=vs.98%29.aspx

[部分答案]:您并不总是返回 ActionResult,不。以下是您可以返回的其他一些结果的快速视图:http: //msdn.microsoft.com/en-us/library/dd410269%28v=vs.98%29.aspx

Maybe that'll help a little. Good luck!

也许这会有所帮助。祝你好运!

回答by eu-ge-ne

Yes, you can define your action like: public ViewResult Index(). But sometimes your action can return different results (it is impossible without declaring result as base ActionResultclass). For example:

是的,你可以定义你的行动,如:public ViewResult Index()。但有时您的操作可能会返回不同的结果(不将结果声明为基ActionResult类是不可能的)。例如:

public ActionResult Show()
{
    ...

    if(Request.IsAjaxRequest())
    {
        return PartialView(...);
    }

    return View(...);
}

or:

或者:

public ActionResult Show()
{
    ...

    try
    {
        ...
    }
    catch(Exception)
    {
        return RedirectToAction(...);
    }

    return View(...);
}

回答by GalacticCowboy

ActionResult is the base class for the various return types. So your action must return an ActionResult or a class derived from itin order to work. Common ones are ViewResult, JsonResult, etc.

ActionResult 是各种返回类型的基类。因此,您的操作必须返回 ActionResult或从它派生的类才能工作。常见的有ViewResultJsonResult等等。

回答by Galaxis

Yep I have Sanderson's book, and I liked that part about being specific, as that was something vexing me when I was looking at other controller action examples. My philosophy even b4 learning MVC was that since functions (methods that return a value) should be treated as if you were declaring a variable/be substitutable in context for a variable/ref of the same type, be specific about the type, as you would if declaring a var (think of it as wanting to avoiding defnining all your variables as type "Object" in an app - more robust, but you lose some design-time checking and type safety). Facilitates a controller unit test for the correct return type as well.

是的,我有 Sanderson 的书,我喜欢具体的那部分,因为当我查看其他控制器动作示例时,这让我很烦恼。我的哲学甚至 b4 学习 MVC 是,因为函数(返回值的方法)应该被视为好像你在声明一个变量/可以在上下文中替换相同类型的变量/引用,请具体说明类型,就像你一样如果声明一个 var (将其视为想要避免在应用程序中将所有变量定义为“对象”类型 - 更健壮,但会丢失一些设计时检查和类型安全)。也有助于控制器单元测试以获取正确的返回类型。

For related reference, check out Listkov's Substitution Principle (the "L" in "SOLID") also.

有关相关参考,请查看 Listkov 的替换原则(“SOLID”中的“L”)。