【发布时间】:2013-04-05 19:20:35
【问题描述】:
我正在使用 webapi,MVC 4 项目。 (使用存储库模式和工作单元) 我有两个问题
1) WebApi 的GetById 应该返回实体还是HttpResponseMessage? 如果是HttpResponseMessage,那么应该是……
[System.Web.Http.HttpGet]
public HttpResponseMessage Get(int id)
{
var car = Uow.Cars.GetById(id);
return car == null ? Request.CreateResponse(HttpStatusCode.OK, car) : Request.CreateResponse(HttpStatusCode.NotFound,);
}
或
[System.Web.Http.HttpGet]
public HttpResponseMessage Get(int id)
{
var car= Uow.Cars.GetById(id);
if (car!= null) {
return car;
}
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
}
我想关注 RESTfull 响应。
2) 将 webapi 服务与 UI 分开是否合乎逻辑?我的意思是在一个 webapi 项目中,具有基本 ApiController 和 CRUD http 操作的控制器,因此可以直接从任何地方/任何设备调用它们,然后另一个 webapi/MVC4 项目将调用 webapi 项目的服务?
我之所以这样问,是因为在同一个控制器中,服务和返回 View 的处理听起来像是将服务耦合到将使用它的客户端。
例如: 从此(在同一个 webapi 控制器中):
[System.Web.Http.HttpGet]
public HttpResponseMessage Get(int id)
{
var car = Uow.Cars.GetById(id);
return car!= null ? Request.CreateResponse(HttpStatusCode.OK, car) : Request.CreateResponse(HttpStatusCode.NotFound,);
}
public ViewResult Details(long id)
{
return View(Get(id));
}
去这个:
public ViewResult Details(long id)
{
return View(webapiService.Cars.Get(id));
}
在服务中实现 Get。
【问题讨论】:
标签: asp.net-mvc-4 asp.net-web-api