0

I'm working on a webapi, EF5, Windsor Castle in a MVC 4 project, and I have a question...should I return the Entity (or DTO) in the Get method or Should I return an HttpResponseMessage? What's the better way and more standard way to do it?

So, Is it this?

[System.Web.Http.HttpGet]
public HttpResponseMessage GetById(long id)
{
    var branch = Uow.Branches.GetById(id);
    if (branch != null)
    {
        Request.CreateResponse(HttpStatusCode.OK, branch);
    }

    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
}

Or this?

[System.Web.Http.HttpGet]
public Branch GetById(long id)
{
    var branch = Uow.Branches.GetById(id);
    if (branch != null) return branch ;
    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
}
polonskyg
  • 4,269
  • 9
  • 41
  • 93

2 Answers2

3

I will return DTO wrapped in HttpResponseMessage as below:

return this.Request.CreateResponse(HttpStatusCode.OK, branch);

DTO/ViewModel will enable to send only required properties.

HttpResponseMessage allow to send additional status code, for example in case of invalid input, we can send statusCode precondition failed.

if (model.EventDate == null)
            {
                var responseMessage = new HttpResponseMessage();
                responseMessage.StatusCode = HttpStatusCode.PreconditionFailed;
                responseMessage.ReasonPhrase = "Please enter valid EventDate input";
                return responseMessage;

            }
aamir sajjad
  • 3,019
  • 1
  • 27
  • 26
1

Depends. However, in your example, since the two versions of the Get action produce the same reponse, I would return the entity Branch instead of the HttpResponseMessage. That is because the framework will help abstract out the actual creation of the HttpResponseMessage so the action focuses more on the business logic.

If you need more control over the reponse message (i.e. setting a different state code), than I would return the HttpResponseMessage instead.

Hope this helps.

Maggie Ying
  • 10,095
  • 2
  • 33
  • 36