【发布时间】:2017-06-23 09:21:43
【问题描述】:
我正在寻找一些建设性的建议。我正在尝试映射多个控制器端点如何相互交互,这样我最终不会在多个控制器中编写相同的代码。请允许我用一个简单的看板示例来说明。
我在这里考虑两个(或三个)控制器:BoardController、CardController、SubCardController(未定)。现在让我们忽略卡片可以组织成列表的事实,因为我们将有一个 ListController 位于 Board 和 Card 控制器之间。
板控制器:
public class BoardController : ApiController {
// among basic CRUD methods I have a method that returns single board
// implementation #1
// /api/board/getbyid?id=123
public HttpResponseMessage GetById(int id) {
var board = dataStore.GetById(id);
if (board == null)
return Request.CreateResponse(HttpStatusCode.NotFound);
return Request.CreateResponse(HttpStatusCode.OK, board);
}
// implementation #2
// /api/board/getbyid?id=123
public HttpResponseMessage GetById(int id) {
var board = GetById(id);
if (board == null)
return Request.CreateResponse(HttpStatusCode.NotFound);
return Request.CreateResponse(HttpStatusCode.OK, board);
}
[NonAction]
// normally methods like this one I declare as private
// but in this case CardController needs to call this method as well
public static Board GetById(int id) {
return dataStore.GetById(id);
}
}
请允许我澄清dataStore 是对另一个单独负责数据访问的控制器的引用。
卡控制器:
public class CardController : ApiController {
// among basic CRUD methods I might want to call BoardControllers GetById(id) method (to verify if board exists for example)
// implementation #1
public HttpResponseMessage GetAll(int boardId) {
// call BoardController.GetById(id) by issueing HTTP request
HttpRequestMessage _request = new HttpRequestMessage(HttpMethod.Get, requestUri);
HttpResponseMessage _response = Client.SendAsync(_request).Result;
Board board = _response.Content.ReadAsAsync<Board>().Result;
if (board == null /* || more condition(s) */)
return Request.CreateResponse(HttpStatusCode.NotFound);
// get cards and return
}
// implementation #2
public HttpResponseMessage GetAll(int boardId) {
// call BoardController.GetById(id) static method
var board = _boardCtrl.GetById(boardId);
if (board == null /* || more condition(s) */)
return Request.CreateResponse(HttpStatusCode.NotFound);
// get cards and return
}
}
这是我的两个替代解决方案。一方面实现#1 不需要额外的静态方法,但另一方面,我认为从一个控制器操作发出 HTTP 请求以访问另一个控制器操作是不好的。
让我知道你们的想法。特别是如果有更整洁的选择。
【问题讨论】:
-
创建一个服务并将其注入您的控制器以访问您想要的模型。尽量让你的控制器保持精简。不需要控制器中的所有逻辑。使用注入服务方法可以在需要的地方重用它。
-
@Nkosi 这是一个快速响应。我想我明白你在说什么,但我不知道如何实现它。你能把我链接到一个很好的例子吗?干杯。
-
@Nkosi 我想我找到了你想要的东西:asp.net/web-api/overview/advanced/dependency-injection
标签: c# asp.net asp.net-web-api architecture