諮詢區
-
Alex Sanséau:
我是 ASP.NET Core Web API 的初學者,我在跟着文檔創建 Controller 時,VS模板引擎給我生成了如下 Controller 模板代碼,我發現有一個奇怪的地方如下:
public class TodoController : Controller
{
}
但文檔中給出的Controller模板是下面這樣的。
[Route("api/[controller]")]
[ApiController]
public class TodoController : ControllerBase
{
}
對,就是 Controller 和 ControllerBase 的問題,我真的很想知道爲啥要用 ControllerBase 而不是 Controller 呢?
回答區
-
Henk Holterman:
其實兩者並沒有嚴格區別,如果往細處說,Controller 是繼承於 ControllerBase 的,同時子類添加了一些爲 MVC 中的 Views 設計的一些屬性和方法,參考如下代碼:
public abstract class Controller : ControllerBase
{
//
// Summary:
// Gets the dynamic view bag.
public dynamic ViewBag { get; }
public ViewDataDictionary ViewData { get; set; }
//
// Summary:
// Gets or sets Microsoft.AspNetCore.Mvc.ViewFeatures.ITempDataDictionary used by
// Microsoft.AspNetCore.Mvc.ViewResult.
public ITempDataDictionary TempData { get; set; }
}
如果你寫的是 API 程序,那自然 ControllerBase 更適合需求,雖然兩者都可以用。
我記得第一版MVC並沒有 ControllerBase,它是後來添加的,所以這取名看起來怪怪的。
-
Mark:
可以看下官方文檔:https://docs.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-3.1
你應該就明白,當你想創建MVC項目時可使用 Controller 父類,如果是WebAPI項目可使用 ControllerBase 類。
另一個不同點在於,ControllerBase 是一個抽象類,所以它沒有方法實現,自然也就沒有Dispose方法了,這裏要注意一下。
點評區
兩位大佬說的很清楚了,學習了。
本文分享自微信公衆號 - 一線碼農聊技術(dotnetfly)。
如有侵權,請聯繫 [email protected] 刪除。
本文參與“OSC源創計劃”,歡迎正在閱讀的你也加入,一起分享。