我正在按照本教程创建 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 ofController
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/