I’m working with webapi, MVC 4 project. (using repository pattern and Unit of Work)
I have two questions
1) The GetById of WebApi should return the entity or HttpResponseMessage?
If it’s HttpResponseMessage, then Should it be…
[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,);
}
or
[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));
}
I’d like to follow RESTfull responses.
2) Is it logical to separate webapi services from the UI? I mean in one webapi project, the controllers with base ApiController and CRUD http opearations, so they can be called from anywhere/any devices directly, and then another webapi/MVC4 project which will call the services of the webapi project?
I’m asking this because having in the same controller the service and the handling that return a View for example sounds like coupling the service to the client which will be consuming it.
For example:
From this (in the same webapi controller):
[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));
}
Go to this:
public ViewResult Details(long id)
{
return View(webapiService.Cars.Get(id));
}
Having the implementation of the Get in the service.
You could use
HttpResponseMessageor the entityCaras the return type. If you useHttpResponseMessageyou would get more control on customizing some of the HTTP properties when you create the response.When the action creates a resource then using the
HttpResponseMessageas the return type provide you much flexible option to set the status code (201) and the location where the created resource can be accessed. See this post for more info.REST not care about which way you use all it cares is when the caller asks for a resource the server should return the resource in a format that the caller can accept it with proper status code (200 if exists else 404).
You can move the WebAPI controllers into separate project if there is really a choice that the service could be consumed from different clients else avoid doing that. Once you move the WebAPI controllers into a separate project then you will face Cross-Domain issues when you try to consume it from the javascript in MVC project.