为什么Web API控制器需要从ControllerBase
而不是Controller
派生.
这不是严格必要的,只是更切题而已.Controller
类派生自ControllerBase
,并添加了一些仅用于支持视图的成员.
基本上:
public abstract class Controller : ControllerBase
{
public dynamic ViewBag { get; }
public virtual ViewResult View(object model) { }
// more View support stuff
}
当您编写API时,ControllerBase会更好地满足您的需求,但两者都可以工作.
每documentation个(强调我的):
不要通过从控制器类派生来创建web API控制器.控制器源于ControllerBase,并添加了对视图的支持,因此它用于处理网页,而不是web API请求.这条规则有一个例外:if you plan to use the same controller for both views and web APIs, derive it from Controller.
我似乎记得在第一次MVC迭代中没有ControllerBase,它是后来插入的.因此,命名/继承 struct 有点奇怪.