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# - 如何从 Excel 2010 为所有三个日期兼容性设置生成 SpreasheetML 示例?

asp.net - 允许服务器/用户控件上的任何属性/属性

C# ASP.NET 通过通用方法绑定(bind)控件

c# - Web API 一次操作即可完成复杂和原始参数

c# - 为什么 visual studio 为程序集重定向创建 app.configs?

c# - 将文件上传到 Azure 上托管的 ASP.NET Core Web 应用程序的目录

java - C# 中用于 Java DES 加密的等效代码?

c# - 如何在 Web 服务器和站点服务器之间建立双向通信?

c# - wcf 服务(REST 或 SOAP 或 WEB API)接受任何结构的任何数据

asp.net-web-api - 添加角色声明 - 我应该使用 IClaimsTransformer