c# - 为什么派生自 ControllerBase 与 Controller for ASP.NET Core Web API?

标签 c# asp.net asp.net-web-api asp.net-core

我正在按照本教程创建 ASP.NET Core Web API,在添加 Controller 的部分中,本教程提供了用于替换 Controller 模板代码的代码。真正引起我注意的一件事是在模板代码中,我得到:

TodoController : Controller

然后在我应该使用的教程代码中,我发现:

[Route("api/[controller]")]
[ApiController]
TodoController : ControllerBase

我很想知道为什么 Web API Controller 必须从 ControllerBase 而不是 Controller 派生。为什么要这样做?

最佳答案

why it is necessary to derive from ControllerBase instead of Controller for a Web API controller.

这不是绝对必要的,只是更重要。 Controller 类派生自 ControllerBase 并添加了一些只需要支持 View 的成员。

基本上:

public abstract class Controller : ControllerBase
{
    public dynamic ViewBag { get; }
    public virtual ViewResult View(object model) { }
    // more View support stuff
}

当您编写 API 时,ControllerBase 会更好地满足您的要求,但两者都可以工作。

来自 the documentation (强调我的):

Don't create a web API controller by deriving from the Controller class. Controller derives from ControllerBase and adds support for views, so it's for handling web pages, not web API requests. There's an exception to this rule: if you plan to use the same controller for both views and web APIs, derive it from Controller.

我好像记得第一次MVC迭代时没有ControllerBase,是后来插入的。因此,有点奇怪的命名/继承结构。

关于c# - 为什么派生自 ControllerBase 与 Controller for ASP.NET Core Web API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55239380/

相关文章:

c# - 从两行获取字符串的正则表达式模式

c# - 我的 C# 代码在 Visual Studio 2013 上无法正常工作

c# - Facebook 喜欢 Ext3 按钮的通知图标

asp.net - 将旧版 ASP.NET 迁移到 MVC 2 (RC) : HttpApplication events not firing, 用户主体为空

asp.net-web-api - 无法在 Mono/xsp4 中加载类型 'System.Web.Http.WebHost.HttpControllerHandler'

c# - 如何使用 api 连接器和 asp net core web api 通过自定义声明丰富 azure b2c token

c# - IndexOf() 与 Replace() 和零宽度非连接器

c# - 使用 C# 从 Visual Studio 下拉菜单中缺少控件

asp.net-mvc-4 - 你必须调用 "WebSecurity.InitializeDatabaseConnection"... 但我已经有了

c# - 从配置文件启动一个字符串