What is the "correct" way to have a call to a Web API REST service that simply returns a single integer?
I have no requirements here in terms of XML, JSON, or anything else. The call to the service just needs to return an integer.
Do I use the ResponseType
attribute here?
I have the service return type as HttpResponseMessage
, and for services such as something returning JSON I would set the Content property on this to StringContent
with UTF8 "application/json".
But what is correct for a single integer?
You can implement your own content type deriving from
HttpContent
class, which is marked asabstract
.StringContent
derives indirectly from it by inheriting fromByteArrayContent
.Generally it depends on the real "meaning" of your
int
. If this is some kind of an identifier, I'd wrap it into some kind of an object.Well, depending on what you wanted to response body to look like. Just a number:
A JSON object containing the number:
I recommend that you use the IHttpActionResult type for your API methods. It will allow you to use several different convenience methods for returning common responses. In your case it would just look like this:
or if you wanted to return it wrapped in an object for easier JSON consumption an anonymous object is fine:
Documentation here
Summarized from the docs are some of the reasons why you would use IHttpActionResult: