16

What seems to be general practice in Web API for return types from action methods?

Returning CLR objects like so:

public IEnumerable<ContactModel> Get()
{
    return _contactService.GetAllForUser();
}

Or wrapping your object in a HttpResponseMessage:

public HttpResponseMessage Get()
{
    IEnumerable<ContactModel> contacts = _contactService.GetAllForUser();

    return Request.CreateResponse((HttpStatusCode) 200, contacts);
}

I prefer having my own CLR objects as the return type as it is obviously results in cleaner methods, as you don't have to mess around instantiating a HttpResponseMessage every time.

2
  • AFAIK, if you return CRL types, in case of exception, the exception message propagates to the client, which is not a good practice. Commented Sep 4, 2012 at 13:07
  • Obviously it's not - but look at @Claudio's answer, he suggests that you can catch exceptions and return appropriate responses to the client using HttpResponseException Commented Sep 4, 2012 at 13:17

2 Answers 2

18

The important point here is that this choice is a matter of PREFERENCE. If you are creating a "URI-Style" HTTP api where the return types are known, in advance, by the client then this may be your preferred approach.

However, personally, I don't like returning CLR types. I believe that by taking this approach you are likely to lose many of the benefits of HTTP. I always return HttpResponseMessage.

If you consider a standard procedure call, there are two possible outcomes, you get the return type back or you get an exception. HTTP interactions are far more flexible than that due to redirects, temporary unavailable servers, no-content, not-modified, server conneg, prefer header variants, etc.

I think that the ApiController class is the place where your application gets the chance to map object-oriented method calls into HTTP request/responses. I think doing this mapping explicitly facilitates taking advantage of HTTP. Letting the framework magically convert the CLR type into some wire representation, does save some typing, but it obscures what is happening and forces you to do any kind of HTTP interactions indirectly through ActionFilters and MessageHandlers.

I have no interest in convincing people who would prefer to return CLR types to change, I simply want to re-assure people who like the idea of returning HttpResponseMessage that it is a completely viable option despite the fact that you will not see many samples like that.

Sign up to request clarification or add additional context in comments.

5 Comments

+1 One benefit to using HttpResponseMessage is that you can return an "error type" in the case of a bad request or server error, instead of having to try and tack on errors to your empty CLR object because you're tied to that particular return type.
I just create a generic ReturnMessages class that has a ReturnClass value that holds the CLR object. This class also holds a return code, return message and any relevant data needed incase a mishap happens. This way I can return the same class for all messages and than check the type when I'm consuming it.
@user3241191 Adding metadata into the return body is redundant. HTTP headers are designed for adding meta to a message. Inventing your own metadata conventions is a waste of effort and will seriously limit your ability to integrate with other systems if the need arises.
How would it seriously limit my ability to integrate with other systems? It is basically spitting back a json style object that is consistent across all API returns. So the consuming code really only needs to be written once and can be re-used across the board. If a system can interact with a JSON style returned object, than there really is no serious limitation.
@user3241191 Believe it or not, not all systems on the web use json. How would you return a response to a client who sends accept: text/plain?
4

I think the first option is the best. In any case if there is no error the return code will be 200 without any setting on your side.

If there is any exception you could throw a HttpResponseException with the appropiate code and message

throw new HttpResponseException(
    Request.CreateResponse<string>(HttpStatusCode.BadRequest, 'Your message'))

8 Comments

I have tried throwing a HttpResponseException from my action method in this way but I just seem to get an empty 200 response on the client?
that shouldn't be the case. I'm doing this myself and works as expected. Please double check your logic.
ahhh yes it does work I must have been doing something wrong the last time I attempted it
just one more thing - if I throw HttpResponseException like so: throw new HttpResponseException(Request.CreateResponse((HttpStatusCode)401, "Unauthorized msg")) - the response body is empty. How do you put a message in the body?
@ClaudioRedi Why do you see Option 1 as "better" than Option 2?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.