我正在開始學(xué)習(xí) asp.net core,并且在理解一些基本模式方面遇到問題。我可以在 PageController 中使用 ApiController 嗎?例如//Home controllerpublic async Task<IActionResult> Index(){ var artists = await _artistController.GetAll(); var t = artists.GetValue(); var indexModel = new Models.Pages.IndexModel { Artists = artists.GetValue() //Extension method }; return View(indexModel);}//ArtistRestController[HttpGet]public async Task<ActionResult<IEnumerable<Artist>>> GetAll(){ try { return Ok(await _repository.GetAll()); } catch (Exception ex) { _logger.LogError(ex.Message); return BadRequest(ex.Message); }}它可以工作,但是設(shè)計(jì)上可以嗎?也許我應(yīng)該直接調(diào)用_repository.GetAll()而不使用其他控制器?
1 回答
12345678_0001
TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超5個贊
首先,您應(yīng)該避免在一個控制器中使用另一個控制器。對于Controller來說,它用于處理來自客戶端的http請求。即使它是一個類,但將其用作一個類是不合理的。
其次,組合起來ApiController會使PageController你的應(yīng)用程序不穩(wěn)定并且耦合性太強(qiáng)。如果您稍后更改任何內(nèi)容ArtistRestController.GetAll都會HomeController損壞。而且,對于您當(dāng)前的代碼,如果 中存在一些異常PageController,您的ApiController代碼將會失敗。
您應(yīng)該注入repository來查詢數(shù)據(jù)。
- 1 回答
- 0 關(guān)注
- 146 瀏覽
添加回答
舉報
0/150
提交
取消
