IController vs ControllerBase vs Controller vs MyController? [英] IController vs ControllerBase vs Controller vs MyController?

查看:77
本文介绍了IController vs ControllerBase vs Controller vs MyController?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正在构建的ASP.NET MVC项目,当我遇到Controller类的实现方式时,我正在浏览一些文档.我对OOP非常熟悉,但是对于为什么以这种方式实现它有一些疑问.

I have an ASP.NET MVC project I have been building and was looking through some documentation when I came across how the Controller class is implemented. I am pretty familiar with OOP but have a few questions about why it is implemented in such a manner.

我查看了代码项目和一些堆栈溢出问题,但找不到我想知道的完全相同的问题.

I looked on codeproject and some stack overflow questions but couldn't find quite the same question I am wondering.

    MVC 5中的
  1. 该链的用途是:IController-> ControllerBase-> Controller-> MyController.
  2. 如果应该说ControllerBase是制造控制器所需的最少费用,那么为什么要有Controller类呢?反之亦然,如果Controller是最低实现,那么ControllerBase并不是真正的基类吗?

提前谢谢!

推荐答案

在MVC 5中,ControllerBase仅充当基本类,主要用于内部使用,并在内部实现IController.Execute(RequestContext requestContext),这是用法列表我来自Resharper

In MVC 5, ControllerBase only acts simply like a base class for mostly internal usage and internally implements the IController.Execute(RequestContext requestContext), and here is the list of usages I got from Resharper

Controller然后实现过滤器,模型和视图绑定的所有功能.因此,要实现您的MyController,您需要从Controller

The Controller then implements all of the features for filters, model and view binding. Therefore, to implement your MyController, you need to derive from Controller

您的参考已经解释了ControllerBaseController的目的.

Your SO reference already explained the purpose of ControllerBase and Controller.

当ASP.NET团队将MVC,WebAPI整合到一个框架中时,在MVC 6(后来称为ASP.NET MVC Core)中看起来更有趣了

Thing look a lot more interesting in MVC 6 (subsequently called ASP.NET MVC Core) when ASP.NET team converged MVC, WebAPI into one framework

请查看GitHub中用于ASP.NET Core 1.1.1的Controller和ControllerBase类的源代码.在每个类的<summary>标记中,他们说:

Please look at the source code for the Controller and ControllerBase class in GitHub for ASP.NET Core 1.1.1. In the <summary> tag for each class, they say:

控制器. cs

具有视图支持的MVC控制器的基类.

A base class for an MVC controller with view support.

ControllerBase. cs

MVC控制器的基类,没有视图支持.

您可能会询问何时使用ControllerBase.我的直觉告诉我,如果我仅将ASP.NET MVC用于WebAPI,并且不需要View功能,则可以直接从ControllerBase派生MyController.在大多数情况下,即使您不使用View且仅返回WebAPI的字符串或JSON,也可以从Controller派生. Controller.cs允许您返回View并利用自动绑定功能.

You may ask when to use ControllerBase. My instinct tells me that if I only use ASP.NET MVC for WebAPI and doesn't require the View feature, you could derive your MyController directly from ControllerBase. Most of the time, you could derive from Controller even if you don't use View and only return string or JSON for WebAPI. Controller.cs allows you to return a View and take advantage of the auto binding.

这篇关于IController vs ControllerBase vs Controller vs MyController?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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